Foreach语句仅显示数据库中的1条记录而不是假定的数量

时间:2015-03-17 19:20:31

标签: php

我从数据库中选择行。当我print_r它显示3条记录,但在我的第2个foreach中它只显示1条记录。

      //get productid
        $product = $database->prepare("SELECT * FROM bids,orders,products WHERE bids.bids_username=? AND NOW() > products.enddate AND orders.orders_status=0 GROUP BY bids.bids_item ORDER BY bids.bids_amount DESC");
        $product->execute(array($username->username));
        $productid = $product->fetchAll();

        print_R($productid);
        //check if order is in database
        foreach($productid as $product):
            $order = $database->prepare("SELECT * FROM orders WHERE orders_product=? AND orders_username=?");
            $order->execute(array($product->bids_item, $username->username));
            $result = $order->fetchAll();
        endforeach;

        //insert order
        if(!$result):
        $createorder = $database->prepare("INSERT INTO orders(orders_username,orders_product,orders_firstname, orders_lastname, orders_address1, orders_address2, orders_zipcode, orders_city, orders_country, orders_btcaddress, orders_status) VALUES(?,?,?,?,?,?,?,?,?,?,?)");
        foreach($productid as $product):
        echo  $product->bids_item;
               //get btc address, check it's valid, then if isset run query below
               $createorder->execute(array($username->username, $product->bids_item, $username->firstname, $username->lastname, $username->address1, $username->address2, $username->zipcode, $username->city, $username->country, 'jkjkjk', 0));
               return 1;
        endforeach;
        endif;

我回应了bid_item它只显示1个结果,它应该贯穿所有3并且全部回显。我的代码中有什么东西看起来不对吗?

2 个答案:

答案 0 :(得分:0)

在你的第二个foreach中,只需替换

$result[] = $order->fetchAll();

您将收到一个数组。目前,您正在覆盖foreach循环的下一个值。如果你愿意的话,请在下一个foreach做同样的事。

答案 1 :(得分:0)

错误在于你的第二个foreach循环

foreach($productid as $product):
    echo  $product->bids_item;
    //get btc address, check it's valid, then if isset run query below
    $createorder->execute(array($username->username, $product->bids_item, $username->firstname, $username->lastname, $username->address1, $username->address2, $username->zipcode, $username->city, $username->country, 'jkjkjk', 0));
   return 1;
endforeach;

return语句导致所有执行停止第一次运行。删除return语句,它应该按预期运行。