0

I have written a very simple php script with the goal connect to mysql database, retrieve data and echo the data. The script is as follows:

<?php
// Include config file
require_once 'config.php';

// Prepare a select statement
$get_query = "select * from dishes";

$stmt = $mysqli->prepare($get_query);
$stmt->execute();
$stmt->store_result();
$result = $stmt->get_result();

//create array to put the table in
$response = array();
$response['dishes'] = array();

while($dishes = $result->fetch_assoc()){
    //create a temporary array
    $temp = array();

    //inserting the dishes in the temporary array
    $temp['unique_id'] = $dishes['unique_id'];
    $temp['title']=$dishes['title'];

    //push the temporary array inside response
    array_push($response['dishes'],$temp);
}

echo json_encode($response);

?>

In the config file are necessary things to connect to my database. The table dishes is very simple, it has 2 columns, one for a unique_id and one with a title. The script is self explanatory as I supplemented comments in it. But if I run it, I get the following error:

PHP Fatal error: Uncaught Error: Call to a member function fetch_assoc() on boolean in ...

where the dots point to this file. I dont understand why this happens. Thank you!

Qirel
  • 25,449
  • 7
  • 45
  • 62
etotheipi
  • 49
  • 1
  • 10

2 Answers2

0

Remove

$stmt->store_result();
Shubham
  • 1,288
  • 2
  • 11
  • 32
-1

Why using a While loop when u can use fetch_all().

$stmt = $this->conn->prepare("select * from dishes");
if ($stmt->execute()) {
        $dishes = $stmt->get_result()->fetch_all();
        $stmt->close();
}