xodebox95 xodebox95 - 8 months ago 19
PHP Question

Error mysqli_fetch_array() expects parameter

I am getting an error mysqli_fetch_array() expects parameter 1 to be mysqli_result in

<?php while($row = mysqli_fetch_array($search)):?>.
I want to search and display information based on the session variable "data" from another page. But I can't seem to display it. May I know what is wrong with the $search?

if (isset($_SESSION["data"])) {
$value = $_SESSION["data"];
$query = "SELECT * FROM datas WHERE CONCAT(name) LIKE '%".$value."%'";
$search = filterTable($query);
$query = "no data found";
$search = filterTable($query);
function filterTable($query)
$connect = mysqli_connect("localhost", "root", "", "databasename");
$filter = mysqli_query($connect, $query);
return $filter;

<div class="table-responsive">
<table class="table table-striped">
<?php while($row = mysqli_fetch_array($search)):?>
<tr class="text-nowrap">
<td><?php echo $row['code'];?></td>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['ID'];?></td>
<td><?php echo $row['cost'];?></td>
<td>hardcoded data</td>
<td><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Book</a></td>
<?php endwhile;?>


You run into that problem because your query errors out, but you still try to use its results. Specifically, when there is no usable data with which to query the database, you still run the query:

if (isset($_SESSION["data"])) {...}
   $query = "no data found";
   $search = filterTable($query);//WHY?

This will cause you problems because no data found is not a legal query. It will error and return FALSE which in turn causes problems to fetch_array

Instead, change your filterTable function to return all the rows you need, or an empty array if there is no match:

$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;

And in your script, do

if(isset($_SESSION['data'])) $rows = filterTable($query);
else $rows = [];

Now, later in your script you can output your results with a:

foreach($rows as $row){
    ...output $row