开发者

How can i display an array outside the for each loop?

开发者 https://www.devze.com 2023-04-08 15:17 出处:网络
So I have a shopping cart that works fine, but I want to display the results of the shopping cart inside a contact form outside of the for each loop.

So I have a shopping cart that works fine, but I want to display the results of the shopping cart inside a contact form outside of the for each loop.

The problem I am having is whenever I try to display $Ptitle it just displays the last addition to the shopping cart. Not the full list of titles inside the array. I have tried various methods to display the array results, but none seem to work. And it seems i can print the array via

print_r ($contents);

But only inside the for each loop, not outside. Below is the code, sorry if it's messy. Any help would be appreciated.

Thank you!

function showCart() {
global $db;
$cart = $_SESSION['cart'];
if ($cart) {
    $items = explode(',',$cart);
    $contents = array();
    foreach ($items as $item) {
        $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1: 1;

    }
    echo '<form action="http://www.changecompanies.net/dev/theme/cart_checkout.php?action=update" method="post" id="cart">';开发者_JAVA技巧
    //$output[] = '<table>';
    ?>
    <table id="cart">
                <tr>
                    <th>Quantity</th>
                    <th></th>
                    <th>Item</th>
                    <th>Product Type</th>
                    <th>Unit Price</th>
                    <th>Total</th>
                    <th>Remove</th>
                </tr>
    <?php
    foreach ($contents as $id=>$qty) {



        $sql = 'SELECT * FROM tccproducts WHERE id = '.$id;
        $result = $db->query($sql);
        $row = $result->fetch();
        extract($row);

        $result = mysql_query("SELECT * FROM tccproducts WHERE Pid ='$id'")or die (mysql_error());
        //if (!$result);
        //echo "no result";
        $myrow = mysql_fetch_array($result) or mysql_error('error!');
        $name = $myrow['Ptitle'];
        //$name = substr($name,0,40);
        $Pprice = $myrow['Pprice'];
        $Ptitle = $myrow['Ptitle'];
        $Pimage = $myrow['Pimage'];
        $Pcat = $myrow['Pcategory'];
        $mini = $myrow['Pminimum'];

Rest just displays the cart and ends the for each loop.


You're running a loop on all the items in the cart, fetching details about that item, then storing the details in individual variables. On every iteration of the loop, the data you retrieve previously gets overwritten by the next row of data fetched. As such, you only ever store the data from the LAST item fetched.

If you want to store all of the item data, you'll have to store each row in an arrow and output afterwards, or just output each row as it's fetched.

while($row = mysql_fetch(...)) {
     echo <<<EOL
<tr>
    <td>{$quantity}</td>
    <td>{$row['price']}</td>
    etc...
</tr>
EOL;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号