php

Possible Duplicate:
Warning: mysql_fetch_* expects parameter 1 to be resource, boolean given error

I'm getting this error message: Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:xampphtdocs...

It only happens when the page loads for first time. (but used to happen if button clicked with no data in form - resolved with javascript validation)

Can anyone tell me where I'm going worng here? There error is on line 49 which is.....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();

?>

Your query fails on the first page load, because you have not yet submitted the form. This results in invalid syntax with an empty LIMIT clause.

Do not execute your query unless $_POST['numberofsentences'] is populated. Furthermore, make sure you have filtered the POST field to be a number, as your script is vulnerable to SQL injection in its current form.

// 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/69222.html

上一篇: mysqli问题得到连接

下一篇: PHP