0

I have a showProduct.php file from where i want to call a function showProduct() in another file. In showProduct() i want to extract all rows from database and to showProduct.php file. the issue is that when i return the array only last row is showing. I want to show all the rows. The showProduct.php is:

<?php
require_once '../includes/DbOperations.php';
$response = array();
$result = array();
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$db = new DbOperations();
$result = $db->showProduct();
if(!empty($result))
{
    $response["prod_name"] = $result["prod_name"];
    $response["prod_desc"] = $result["prod_desc"];
    $response["prod_image"] = $result["prod_image"];
}
else
{
    $response["error"] = true;
    $response["message"] = "products are not shown";
}
} 
echo json_encode($response);
?>

and showProduct() function is:

public function showProduct(){
    $menu = array();
    $query = mysqli_query($this->con,"SELECT * FROM `products` WHERE 1");
    while ($row = mysqli_fetch_array($query)) {
            $menu['prod_name'] = $row['prod_name'] ;
            $menu['prod_desc'] = $row['prod_desc'] ;
            $menu['prod_image'] = $row['prod_image'];
    }
    return $menu;
}

1 Answer 1

2

In your function, you are just overwriting the last data each time, you need to build this data up. Create an array with the new data and use $menu[] to add this new data to the list of menus...

public function showProduct(){
    $menu = array();
    $query = mysqli_query($this->con,"SELECT * FROM `products` WHERE 1");
    while ($row = mysqli_fetch_array($query)) {
            $newMenu = [];    // Clear array to ensure no details left over
            $newMenu['prod_name'] = $row['prod_name'] ;
            $newMenu['prod_desc'] = $row['prod_desc'] ;
            $newMenu['prod_image'] = $row['prod_image'];

            $menu[] = $newMenu;
    }
    return $menu;
}
Sign up to request clarification or add additional context in comments.

Comments

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.