php pdo在循环中执行多个查询

时间:2017-04-27 11:28:18

标签: php pdo

首先选择查询,如果id存在则只更新数量,否则执行insert(id, quantity)查询 在我的情况下只是更新查询执行

$fodid = $data->orfid;
$quantity = $data->orqnt; 

include('db.php');     

try{                              
    $sqlchk="SELECT `orfoodid` AS  FROM `orders` where `orfoodid`=':chkfoodid';";
    $sqlupdate="UPDATE `resturant`.`orders` SET `orfoodqnt` = ':chcount' WHERE `orders`.`orfoodid` = ':chfodid';";
    $sql="INSERT INTO `resturant`.`orders` (`orfoodid`, `orfoodqnt`) VALUES (:foodid,:count);";  

    for($i=0;$i<sizeof($fodid);$i++){

        $rs = $conn->prepare($sqlchk);
        $rs->execute(array(':chkfoodid'=>$fodid[$i]));       
        $result=$rs->fetch(PDO::FETCH_ASSOC);     

        if(!$result)
        {
            $rs = $conn->prepare($sqlupdate);
            $rs->execute(array(':chfodid'=>$fodid[$i],
                           ':chcount'=>$quantity[$i]));
            echo 'Order updated';                      
        } else {         
            $rs = $conn->prepare($sql);
            $rs->execute(array(':foodid'=>$fodid[$i],
                           ':count'=>$quantity[$i])); 
            echo 'Order Saved';
        }           

    }                          
    $conn=null;
}catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

1 个答案:

答案 0 :(得分:0)

我解决了我的问题,这是语法错误 &#39;:chkfoodid&#39;只需删除单引号:chkfoodid