PHP

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

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

它只发生在第一次加载页面时。 (但过去发生,如果按钮点击没有数据的形式 - 解决与JavaScript验证)

有谁能告诉我我要去哪里吗? 第49行有错误,是..... while($ 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();

?>

您的查询在首页加载时失败,因为您尚未提交表单。 这会导致语法无效且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();
}
链接地址: http://www.djcxy.com/p/69221.html

上一篇: php

下一篇: Warning: mysql