Reputation: 1084
I want to run a SELECT query and fetch data as associative array
and echo the fetched data.
In procedural style I would use mysqli_fetch_array()
. But I am now trying OOP style
.
I have tried this code:
$con= new mysqli('localhost','root','','afiliate');
$query="SELECT * FROM product WHERE ID=? ";
$stmt->bind_param("i",$ID); /* $ID has a value, it's ok */
$stmt->execute();
$result=$con->query($query);
while($row=$result->fetch_row()){
echo $row['name'];
}
And the error I get is:
Fatal error: Call to a member function fetch_row() on boolean in /opt/lampp/htdocs/afiliate/product_details_individual.php on line 18
How can I fetch data and echo them?
Upvotes: 0
Views: 3033
Reputation: 31654
You're doing two conflicting things
$con= new mysqli('localhost','root','','afiliate');
$query="SELECT * FROM product WHERE ID=? ";
$stmt->bind_param("i",$ID); /* $ID has a value, it's ok */
$stmt->execute();
So at this point $stmt
is a mysql_stmt object. If you have mysqlnd installed you can do this
$result = $stmt->get_result();
while($row=$result->fetch_row()){
echo $row['name'];
}
This line can't work in this code block
$result=$con->query($query);
The SQL you are passing is for a prepared statement and cannot be executed directly using query()
. Your query will fail (returns false
when there is an execution error) and, as a result, you get the error you mentioned
Upvotes: 1