while($row = mysql_fetch_assoc($result)) - How to foreach $row?

70,244

Solution 1

Let's say that each of the rows in your database looks like this...

[product_id][product_name][product_description][product_price]

When you assign your query return to a variable passed through mysql_fetch_assoc() using a while loop, each pass will isolate a whole row. Of which you can piece apart manually by array key reference ($array['product_id']) or by using a foreach loop. I think the problem you're having is that you are mixing this up. Keeping the above example table layout in mind, you could do something like the following:

while ($tableRow = mysql_fetch_assoc($query)) { // Loops 3 times if there are 3 returned rows... etc

    foreach ($tableRow as $key => $value) { // Loops 4 times because there are 4 columns
        echo $value;
        echo $tableRow[$key]; // Same output as previous line
    }
    echo $tableRow['product_id']; // Echos 3 times each row's product_id value
}

Look at this line in your code: if ($product['id'] == $id) { }

I think you probably mean if ($row['id'] == $id) { } instead.

Solution 2

Your middle code block makes no sense. You loop over session variables, and run a query each time... but it's the SAME query, and using an undefined variable to boot. Looping over a result row doesn't make much sense, as you'd be looping over the individual fields that your query returns for each row.

e.g. If your products table has just (id, name, description) as fields, then $row would be an array that looks like:

$row = array('id' => xxx, 'name' => yyy, 'description' => zzz);

When you foreach() on $row(), you'd not getting individual products, you'd be getting those fields in the row. $product would be xxx, then yyy, then zzz.

I don't know what your code is trying to accomplish - I'd guess you're trying to retrieve prices for products that a user is adding into their cart, but you're going about it in a very strange and highly inefficient manner.

Share:
70,244
Craig van Tonder
Author by

Craig van Tonder

Updated on August 07, 2020

Comments

  • Craig van Tonder
    Craig van Tonder over 3 years

    I am working on a simple order system.

    the peice of code I am stuck on is the following:

    if (isset($_GET['cart']))
    {
    $cart = array();
    $total = 0;
    foreach ($_SESSION['cart'] as $id)
    {
        foreach ($items as $product)
        {
            if ($product['id'] == $id)
            {
                $cart[] = $product;
                $total += $product['price'];
                break;
            }
        }
    }
    
    include 'cart.html.php';
    exit();
    }
    

    This is the code is build on a preset array. I am working with a table with a few columns in mysql.

    I have decided on the following:

    if (isset($_GET['cart']))
    {
    $cart = array();
    $total = 0;
    foreach ($_SESSION['cart'] as $id)
    {
                while($row = mysql_fetch_assoc($productsSql)) {
        foreach ($row as $product)
        {
            if ($product['id'] == $id)
            {
                $cart[] = $product;
                $total += $product['price'];
                break;
            }
        }
    }
        include 'cart.html.php';
    exit();
    }}
    

    To display this "cart" I have decided on this:

    foreach ($cart as $item) {
            $pageContent .= '
                    <tr>
                        <td>'.$item['desc'].'</td>
                        <td>
                            R'.number_format($item['price'], 2).'
                        </td>
                    </tr>
    ';
    
        }
    

    All this seems to do is produce my cart in a fashion where when viewed it displays a list of only the items' id, e.g. where the description and price are supposed to be, I only get the items id in both fields... I also get a total price of 0.

    Can anyone spot where I am going wrong here?

    Or atleast try to give me some input so that I get going in the right direction!

    Thanks!!

    $productsQuery = 'SELECT `id`, `refCode`, `desc`, `pack`, `measure`, `quantity`, `deptCode`, `taxable`, `price1`, `price2`, `crdCode`, `cost1`, `cost2` FROM `products` ORDER BY `desc` ';
    $productsSql = mysql_query($productsQuery) or die(mysql_error());
    if (mysql_num_rows($productsSql) == 0) {
    die('No results.');
    } else {
    $orderContent = '';
    while($row = mysql_fetch_assoc($productsSql)) {
    $prId = $row['id'];
    $prRefCode = $row['refCode'];
    $prDesc = $row['desc'];
    $prPack = $row['pack'];
    $prMeasure = $row['measure'];
    $prQuantity = $row['quantity'];
    $prDeptCode = $row['deptCode'];
    $prTaxable = $row['taxable'];
    $prPrice1 = $row['price1'];
    $prPrice2 = $row['price2'];
    $prCrdCode = $row['crdCode'];
    $prCost1 = $row['cost1'];
    $prCost2 = $row['cost2'];
    $orderContent .= '
        <tr>
            <td>'.$prId.'</td>
            <td>'.$prDesc.'</td>
            <td>'.$prPack.'x'.$prSize.' '.$prMeasure.'</td>
            <td>R'.$prPrice1.'</td>
            <td>
                <form action="" method="post">
                    <div>
                        <input type="text" size="3" name="quantity" /> 
                    </div>
                </form>
            </td>
            <td>
                <form action="" method="post">
                    <div>
                        <input type="hidden" name="id" value="'.$prId.'" />
                        <input type="submit" name="action" value="Order" />
                    </div>
                </form>
            </td>           
       </tr>
    ';
    }}