Jamjar91
Jamjar91

Reputation: 25

PHP 5.6 MySQL foreach query returning same value

I have a foreach MySQL query that I expect to return all results with an identical order ID, yet it yields the same product ID. It knows the correct amount of entries with that particular order ID, as the counter stops after running through all entries with the same order ID.

My foreach statement:

$i = 0;
foreach ($_SESSION["cart_array"] as $per_item)
    {
        $item_id = $per_item['latestid'];
        $fetchorder = mysql_query("SELECT ISBN FROM transactions WHERE Order_ID='$latestid'");
        while ($row = mysql_fetch_array($fetchorder))
            {
                $ISBN = $row["ISBN"];   
            };

        echo "ISBNs in order $latestid are: $ISBN";
        echo "<br>";

        $i++;
    };

$latestid is obtained from a previous query, that correctly results in collecting the most recent order ID.

My database table looks like this:

Table: transactions
Order_ID | ISBN
      25 | 11111111
      25 | 22222222
      25 | 33333333

Yet, my yielded results are:

latestid = 25
ISBNs in order 25 are: 33333333
ISBNs in order 25 are: 33333333
ISBNs in order 25 are: 33333333

(The latestid = 25 is echoed from the previous sql query, just for testing purposes to ensure it works correctly.)

What's causing this to display the same item ID (ISBN) when it should list all from that particular order ID?

Thanks in advance,

Jamie.

Upvotes: 0

Views: 348

Answers (2)

Mofiqul Islam
Mofiqul Islam

Reputation: 195

Your echo is not inside the loop so its printing only last assignment to the $ISBN . Place it inside the while loop. your code should be this.

i = 0;
foreach ($_SESSION["cart_array"] as $per_item)
    {
        $item_id = $per_item['latestid'];
        $fetchorder = mysql_query("SELECT ISBN FROM transactions WHERE Order_ID='$latestid'");
        while ($row = mysql_fetch_array($fetchorder))
            {
                $ISBN = $row["ISBN"]; 
                echo "ISBNs in order $latestid are: $ISBN";
                echo "<br>";  
            };
        $i++;
    }

Upvotes: 2

sreeja seguro
sreeja seguro

Reputation: 16

Try this

$i = 0;
foreach ($_SESSION["cart_array"] as $per_item)
    {
        $item_id = $per_item['latestid'];
        $fetchorder = mysql_query("SELECT ISBN FROM transactions WHERE Order_ID='$latestid'");
        while ($row = mysql_fetch_array($fetchorder))
            {
                $ISBN = $row["ISBN"];   
             echo "ISBNs in order $latestid are: $ISBN";
              echo "<br>";
            };




        $i++;
    };

Upvotes: 0

Related Questions