首页 文章

MYSQL_FETCH_ARRAY参数资源错误 . [重复]

提问于
浏览
2

可能重复:警告:mysql_fetch_ *期望参数1是资源,布尔给定错误

我收到此错误消息:警告:mysql_fetch_array()期望参数1是资源,在C:\ xampp \ htdocs中给出布尔值...

它仅在第一次加载页面时发生 . (但是如果点击按钮而没有表格中的数据,则会发生这种情况 - 通过javascript验证解决)

有谁能告诉我我在哪里?第49行出现错误,即.....($ row = mysql_fetch_array($ result))

<?php
$host="localhost"; // Host name 
$username=""; // Mysql username 
$password=""; // Mysql password 
$db_name=""; // Database name 
$tbl_name=""; // Table name 

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

$sn=$_POST['numberofsentences'];


$query="SELECT line FROM sentence ORDER BY rand() LIMIT $sn";
$result = mysql_query($query);

$count = 0;

while ( $row = mysql_fetch_array($result) )
{ 
// do something with $row. The following echos the results and adds a space after each        
//sentence. 
echo $row['line'], "&nbsp"; 
if ($count >= 7) 
{ 
echo '
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; $count = 0; } else { $count++; } } // Close the database connection mysql_close(); ?>

1 回答

  • 1

    您的查询在第一页加载时失败,因为您尚未提交表单 . 这会导致语法无效,并带有空的 LIMIT 子句 .

    除非填充 $_POST['numberofsentences'] ,否则不要执行查询 . 此外,请确保已将POST字段过滤为数字,因为您的脚本易受当前形式的SQL注入攻击 .

    // Verify the field was submitted AND is a valid number
    if (isset($_POST['numberofsentences']) && is_numeric($_POST['numberofsentences'])) {
    
      // Connect to server and select databse.
      // Note that quotes were removed from these variables. Unnecessary and bad practice 
      // to quote them unless they are part of larger interpolated strings.
      mysql_connect($host, $username, $password)or die("cannot connect");
      mysql_select_db($db_name)or die("cannot select DB");
    
      // Cast it to an integer
      $sn = intval($_POST['numberofsentences']);
    
    
      $query="SELECT line FROM sentence ORDER BY rand() LIMIT $sn";
      $result = mysql_query($query);
    
      $count = 0;
    
      // Verify the query succeeded...
      if ($result) {
        while ( $row = mysql_fetch_array($result) )
        { 
          // fetch result and do other stuff...
        }
     }
     // Query failed...
     else echo "An error occurred: " . mysql_error();
    }
    

相关问题