user9355515
user9355515

Reputation:

PHP Does Not Show All Rows From Table

I have a table named cart and I want to return all the rows from it via PHP.

So I coded this:

$get_add = "SELECT * FROM cart WHERE ip_add = '1'";
$run_add = mysqli_query($con,$get_add);

$cart_items = [];
while($row_results = mysqli_fetch_array($run_add))
{
    $item = array(
        'table_id' => $row_results['table_id'],
        'pro_id' => $row_results['product_id'],
        'pro_title' => $row_results['product_title'],
        'pro_price' => number_format($row_results['product_price'], '0', '', ','),
        'pro_supplier'  => $row_results['product_supplier'],
        'pro_img' => $row_results['product_image'],
    );
    $cart_items[] = $item;

    foreach($cart_items as $cart){
        echo $cart['pro_title']
    }
 }

So this works fine but the only problem is that it only shows ONE result. However there are several rows that has same ip_add set to 1.

So I'm begging you to let me know what is my fault and what is the correct way of showing all table rows?

Thanks in advance!

Upvotes: 2

Views: 63

Answers (2)

Amit Merchant
Amit Merchant

Reputation: 1043

Move your inner foreach loop outside of while like this:

while($row_results = mysqli_fetch_array($run_add))
{
    $item = array(
        'table_id' => $row_results['table_id'],
        'pro_id' => $row_results['product_id'],
        'pro_title' => $row_results['product_title'],
        'pro_price' => number_format($row_results['product_price'], '0', '', ','),
        'pro_supplier'  => $row_results['product_supplier'],
        'pro_img' => $row_results['product_image'],
    );
    $cart_items[] = $item;
}

foreach($cart_items as $cart){
    echo $cart['pro_title'];
}

Basically, what you are doing will always return the last item of array $cart_itmes because it's inside of while loop. So, change it to the way I've done in above snippet.

Upvotes: 1

Pankaj Makwana
Pankaj Makwana

Reputation: 3050

Remove foreach loop of $cart_items and add it after while loop. Because you are appending values in $cart_items then you are looping that $cart_items, so first time you will get single value, then two values, and then three values so on... One more thing add ; at the end of echo $cart['pro_title'] line.

while ($row_results = mysqli_fetch_array($run_add)) {
    $item = array(
        'table_id' => $row_results['table_id'],
        'pro_id' => $row_results['product_id'],
        'pro_title' => $row_results['product_title'],
        'pro_price' => number_format($row_results['product_price'], '0', '', ','),
        'pro_supplier' => $row_results['product_supplier'],
        'pro_img' => $row_results['product_image'],
    );
    $cart_items[] = $item;
}

foreach ($cart_items as $cart) {
    echo $cart['pro_title'];
}

Adding foreach at the end will get all the records in the $cart_items.

Upvotes: 1

Related Questions