这个问题在这里已经有了答案:
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
(31 个回答)
6年前关闭。
尝试进行搜索后,我的服务器上不断收到警告,它说:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given inform/search.php on line 19
这是代码,我不太明白为什么它不显示结果。任何帮助将非常感激。
<?php
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['postcode'])){
$postcode=$_POST['postcode'];
//connect to the database
}
$con = mysql_connect('*****','*****','*****'); //connect to the database
if (!$con) //if cannot connect to the database, terminate the process
{
die('Could not connect: ' . mysql_error());
}
$mydb=mysql_select_db("dataproj");
//-query the database table
$sql="SELECT * FROM companies WHERE postcode LIKE '%" . $postcode ."%'";
//-run the query against the mysql query function
$result=mysql_query($sql);
//-create while loop and loop through result set
while($row=mysql_fetch_array($result)){
$postcode =$row['postcode'];
$cname=$row['cname'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . $postcode . " " . $cname . "</a></li>\n";
echo "</ul>";
}
}
else{
echo "<p>Please enter a search query</p>";
}
}
?>
最佳答案
首先不要使用 mysql API 不推荐使用 PDO 或 mysqli。
Secondly Check $result before passing it to mysql_fetch_array. You'll find that it's false because the query failed. See the mysql_query documentation for possible return values and suggestions for how to deal with them.
<?php
if (isset($_POST['submit'])) {
if (isset($_GET['go'])) {
if (preg_match("/^[ a-zA-Z]+/", $_POST['postcode'])) {
$postcode = $_POST['postcode'];
//connect to the database
}
$con = mysql_connect('*****', '*****', '*****'); //connect to the database
if (!$con) { //if cannot connect to the database, terminate the process
die('Could not connect: ' . mysql_error());
}
$mydb = mysql_select_db("dataproj");
//-query the database table
$sql = "SELECT * FROM companies WHERE postcode LIKE '%" . $postcode . "%'";
//-run the query against the mysql query function
$result = mysql_query($sql);
//check here
if ($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$postcode = $row['postcode'];
$cname = $row['cname'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . $postcode . " " . $cname . "</a></li>\n";
echo "</ul>";
}
} else {
echo "<p>Please enter a search query</p>";
}
}
?>
关于未显示 PHP/mySQL 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30842838/