Mysqli INSERT命令后跟UPDATE

时间:2015-01-16 10:48:51

标签: php mysql mysqli prepared-statement

我希望在一个表中插入数据,并通过 mysqli 中的预准备语句在另一个表中更新数据。尝试以下操作仅执行INSERT命令:

编辑:

if($stmt=$mysqli->prepare("SELECT bids_id, bid, fruit_volume FROM basket ORDER BY bid DESC")) {
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($bids_id, $bid, $fruit_volume);                      
    while($stmt->fetch()) { 
        $stack = array($bids_id, $bid, $fruit_volume);
        array_push($all_fruits, $stack);    
    } 
    $stmt->free_result();
}
foreach ($all_fruits as $fruits) {
   if ($_POST["offer"] == $fruits[1] && $volume < $fruits[2]) {
        $stmt2 = $mysqli->prepare("INSERT INTO oranges (username, price, volume, date) VALUES (?, ?, ?, ?)");
        $stmt2->bind_param('sdis', $user, $price, $volume, $today); 
        $stmt2->execute();

        $stmt3 = $mysqli->prepare("UPDATE basket SET fruit_volume = ? WHERE bids_id = ?");
        $stmt3->bind_param('ii', 800, 1);
        $stmt3->execute();  

    }
}
$mysqli->close();

2 个答案:

答案 0 :(得分:2)

试试这个

foreach ($all_fruits as $fruits) {
   if ($_POST["offer"] == $fruits[1] && $volume < $fruits[2]) {
        $stmt2 = $mysqli->prepare("INSERT INTO oranges (username, price, volume, date) VALUES (?, ?, ?, ?)");
        $stmt2->bind_param('sdis', $user, $price, $volume, $today); 
        $stmt2->execute();


        $stmt3 = $mysqli->prepare("UPDATE basket SET fruit_volume = ? WHERE bids_id = ?");
        $stmt3->bind_param('ii', 800, 1);
        $stmt3->execute();            
    }
}
$mysqli->close();

答案 1 :(得分:2)

bind_param通过引用传递而不是按值传递,因此您需要在引用它们之前将这些值包含在变量中

$a=800;
$b=1;

foreach ($all_fruits as $fruits) {
   if ($_POST["offer"] == $fruits[1] && $volume < $fruits[2]) {
        $stmt2 = $mysqli->prepare("INSERT INTO oranges (username, price, volume, date) VALUES (?, ?, ?, ?)");
        $stmt2->bind_param('sdis', $user, $price, $volume, $today); 
        $stmt2->execute();

        $stmt3 = $mysqli->prepare("UPDATE basket SET fruit_volume = ? WHERE bids_id = ?");
        $stmt3->bind_param('ii',$a, $b);
        $stmt3->execute();  

    }
}