在我尝试进行搜索后,我的服务器上一直收到警告:
警告:mysql_fetch_array()要求参数1为资源,布尔给出第19行的/ search.php
继承代码,我不太明白为什么它不显示结果。任何帮助将非常感激。
<?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>";
}
}
?>
答案 0 :(得分:0)
首先不要使用不推荐使用的 mysql API使用PDO或mysqli。
其次在将结果传递给mysql_fetch_array之前检查$ result。你会发现这一点 它是错误的,因为查询失败了。请参阅mysql_query文档 可能的返回值以及如何处理它们的建议。
<?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>";
}
}
?>