0

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?

5
  • have you tried $result->fetch_array(); Commented Jun 16, 2015 at 17:23
  • if (!$result=$con->query($query)) { // in case of unsuccess it returns false; Commented Jun 16, 2015 at 17:25
  • @AshleyWrench >>> Fatal error: Call to a member function fetch_array() on boolean in /opt/lampp/htdocs/afiliate/product_details_individual.php on line 18 Commented Jun 16, 2015 at 17:26
  • You could also push the OOP further by using $result->fetch_object('product'); but you will need to define a class product and have your db returning data matching the class definition. Commented Jun 16, 2015 at 17:27
  • you should use prepare method before bind_param. You don't do it. Your query not correct. $result get false. You use metod with false but object Commented Jun 16, 2015 at 17:35

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

But this using this code, $row['name'] returns a NULL. var_dump($row['name']) just prints "NULL"
What about var_dump($row); ?
array(8) { [0]=> int(1) [1]=> string(5) "watch" [2]=> string(10) "k bollo na" [3]=> string(8) "aer t 4t" [4]=> string(23) "product_images/fwef.png" [5]=> float(100) [6]=> string(7) "general" [7]=> float(5) }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.