scriptkiddie scriptkiddie - 4 months ago 4
MySQL Question

Fatal error: Cannot use object of type mysqli_result as array

I am trying to get the result from my database table

tbl_newpage
but it throws error. I don't know why it throws error

The following line

$page = $mysqli->real_escape_string($_GET['page']);

$result=array();

if($stmt = $mysqli->prepare("select * from tbl_newpage where name=?")){

$stmt->bind_param("s", $page);

$stmt->execute();

$result = $stmt->get_result();

while($row = $result->fetch_array()){

$result[] = array($row); //This is where the error appears
echo "hello ";print_r($row);die();

}

$objSmarty->assign("result", $result);
}


Throws error

Fatal error: Cannot use object of type mysqli_result as array in
/var/www/html/examplesite/phpfile.php
on line 22

Answer

You're using the same variable $result for both the result of $stmt->get_result() and also the array of values that you're fetching. So on the second iteration of the loop, when it does

$row = $result->fetch_array()

$result no longer contains the mysqli result, it contains the array, and you can't call fetch_array() on an array. Use different variable names for them.

$output = array();
while ($row = $result->fetch_array()) {
    $output[] = $row;
}
$objSmarty->assign("result", $output);

Also, $row is already an array, you probably don't want to nest it in another array before pushing it onto the $output array.

Comments