-1

I am trying to create a shopping cart to my php application i already write this code it gives me this error Invalid argument supplied for foreach() and it doesn't retrive the data that are in the database

code is looks like this

<?php

     include('../Neo/assets/session.inc.php');
     include 'config/config.php';

if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

$last_id = mysqli_insert_id($con);
$_SESSION['last_id'] = $last_id;
$sql = "SELECT * FROM product_order WHERE ord_id =" . $last_id;
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_assoc($result);

?>

<?php
                        foreach($row as $i){
                            echo
                                '<tr>
                                <td> '.$i['ord_id'].'</td>
                                <td> '.$i['card_id'].'</td>
                                <td> '.$i['field1'].'</td>
                                <td> '.$i['field2'].'</td>
                                <td> '.$i['field3'].'</td>
                                <td> '.$i['field4'].'</td>
                                <td> '.$i['field5'].'</td>
                                <td> '.$i['ord_qty'].'</td>
                                <td> '.$i['card_price'].'</td>
                                <td> '.$i['ord_total'].'</td>
                                </tr>';
                        }
                        ?>

1 Answers1

0

The mysqli_fetch_assoc function, based on documentation, Fetch a result row as an associative array. For each row, you should call this call this function once:

while($row = mysqli_fetch_assoc($result)) {
    echo $row['ord_id'];
}

But of course, before using this function, it would be better to check the $result and to debug such an error in your code, you can always use var_dump/print_r to see what is the type/value of a variable and also check that the given query is correct or not.

Ali Khalili
  • 1,504
  • 3
  • 18
  • 19
  • i tried this code but it doesn't return anything ` '.$row['ord_id'].' '.$row['card_id'].' '.$row['field1'].' '.$row['field2'].' '.$row['field3'].' '.$row['field4'].' '.$row['field5'].' '.$row['ord_qty'].' '.$row['card_price'].' '.$row['ord_total'].' '; } ?>` – Craft Cover Sep 29 '19 at 06:09
  • `var_dump($row);` this statement returns null is anything wrong with my sql command – Craft Cover Sep 29 '19 at 06:11
  • this statement is not working correctly `$last_id = mysqli_insert_id($con);` – Craft Cover Sep 29 '19 at 06:24
  • For mysqli_insert_id, you should first insert something to db, and it seems you didn't – Ali Khalili Sep 29 '19 at 17:40