我收到错误mysqli_fetch_array()期望参数1是<?php while($row = mysqli_fetch_array($search)):?>.
中的mysqli_result我想根据来自另一个页面的会话变量“data”搜索和显示信息。但我似乎无法展示它。我可以知道$ search有什么问题吗?
<?php
if (isset($_SESSION["data"])) {
$value = $_SESSION["data"];
$query = "SELECT * FROM datas WHERE CONCAT(name) LIKE '%".$value."%'";
$search = filterTable($query);
}
else
{
$query = "no data found";
$search = filterTable($query);
}
function filterTable($query)
{
$connect = mysqli_connect("localhost", "root", "", "databasename");
$filter = mysqli_query($connect, $query);
return $filter;
}
?>
答案 0 :(得分:0)
您遇到了这个问题,因为您的查询错误,但您仍尝试使用其结果。具体来说,当没有可用于查询数据库的数据时,您仍然运行查询:
if (isset($_SESSION["data"])) {...}
else
{
$query = "no data found";
$search = filterTable($query);//WHY?
}
这会导致您遇到问题,因为no data found
不是合法查询。它会出错并返回FALSE
,这会导致问题fetch_array
相反,更改 filterTable 函数以返回所需的所有行,如果没有匹配则更改为空数组:
$connect = mysqli_connect("localhost", "root", "", "databasename");
$result = mysqli_query($connect, $query);
if($result===false) die (mysqli_error($connect));//server error: prob bad query
$rows = mysqli_fetch_all($filter, MYSQLI_ASSOC);//all matching rows
mysqli_close(); //don't forget to close the connection
return $rows;
在您的脚本中,执行
if(isset($_SESSION['data'])) $rows = filterTable($query);
else $rows = [];
现在,稍后在您的脚本中,您可以输出结果:
foreach($rows as $row){
...output $row
}