2011-11-04 110 views
2

可能重复:
Warning: mysql_fetch_* expects parameter 1 to be resource, boolean given errorMYSQL_FETCH_ARRAY参数资源错误。

我收到此错误信息:警告:mysql_fetch_array()预计参数1是资源,在C定的boolean:\ XAMPP \ htdocs中。 ..

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

谁能告诉我,我要去哪里worng吗?有错误是行49这是.....而($行= mysql_fetch_array($结果))

<?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

您所查询的第一页加载失败,因为你还没有提交表单。这会导致语法无效且空的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(); 
} 
+0

因为您不能发布空字符串,isset就足够了。空()是另一个有用的功能。 – malletjo

+0

太棒了。谢谢你的帮助。现在完美运作。感谢您对语法的其他评论。 – user1022772

相关问题