I have this php script in an external file trying to get random question from a db:
<?php
//connect to db
require_once('db.php');
$id=rand(0,13); //2nd number = highest ID
if ($resQ = $mysqli->query("SELECT Quest FROM qa WHERE ID='$id'")){
echo "" . $resQ['Quest'] . ""; //This is Line 9
$resQ->close();
}
$mysqli->close();
?>
and I call it in my page like this
<body>
code...
<?php require_once('script/m_q.php'); ?>
...code
</body>
But i get error:
Fatal error: Cannot use object of type mysqli_result as array in .../m_q.php on line 9
Any help? Thank you
Thank you all... Unfortunatelly I can accept just one answer, si I choose the one that answered first.
mysqli::query does return a result set, you have to fetch rows in order to access the columns.
You have to call the fetch_assoc()
method of the mysqli_result
object to access the data:
<?php
//connect to db
require_once('db.php');
$id=rand(0,13); //2nd number = highest ID
if ($resQ = $mysqli->query("SELECT Quest FROM qa WHERE ID='$id'")){
$data = $resQ->fetch_assoc();
echo "" . $data['Quest'] . ""; //This is Line 9
$resQ->close();
}
$mysqli->close();
?>
You need to fetch the data first.
$rs = $resQ->fetch_assoc();
echo $rs['Quest'];
$resQ cannot get in an if statement... assign data to it 1st using mysql_fetch_assoc or mysql_fetch_array.