MYSQL_FETCH_ARRAY参数资源错误。

时间:2011-11-04 01:41:07

标签: php mysql

  

可能重复:
  Warning: mysql_fetch_* expects parameter 1 to be resource, boolean given error

我收到此错误消息:警告: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 '<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 
$count = 0; 
} else { 
$count++; } }



    // Close the database connection
    mysql_close();

?>

1 个答案:

答案 0 :(得分: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();
}