【问题标题】:How to stop an update if an element is unverified如果元素未经验证,如何停止更新
【发布时间】:2020-04-18 14:04:59
【问题描述】:

我的更新有问题。我更新了我的库存,删除了制作食物所需的数量(库存 = 库存 - :数量),如果我的库存 <=0 我打印出我没有足够的元素来制作食物。

这是我的代码:

<?php
$query1 = "SELECT ingredients.stock as stock,
           composition.id_ingredient,composition.quantite 
            rom composition 
            join ingredients on(composition.id_ingredient = ingredients.id) 
            where id_recette = 1;";

$response1 = $db->query($query1);
$response1->setFetchMode(PDO::FETCH_ASSOC );
foreach ($response1 as $row1) {
    $persons1[] = $row1;
}
$response1->closeCursor();
?>


<?php
if (isset($_GET['burger1']) AND $_GET['burger1'] == 'fabriquer') {
    foreach ($persons1 as $ET10) {
        if($ET10['stock'] - $ET10['quantite']<0){
            echo "Stock insuffisant de: ".$ET10['id_ingredient'];
    ;
        }
    }else if($ET10['stock'] - $ET10['quantite']>=0){
        $req=$db->prepare("UPDATE ingredients SET stock = stock - :quantite WHERE id = :ingredient");
        $req->execute(array(
                'quantite' => $ET10['quantite'],
                'ingredient'  => $ET10['id_ingredient'])
            );
    }
?>
<?php 
}
?>  

问题是我打印了消息,如果我点击我的按钮“fabriquer”,它将继续更新其他元素,它们的(库存 - 数量)> 0。但是我想说,如果我们没有足够的库存,就不可能制作食物。因此,如果无法更新 1 个元素,我想停止更新。

感谢阅读!

【问题讨论】:

    标签: php sql button sql-update


    【解决方案1】:

    您可以检查 where 子句中的条件以进行更新

    UPDATE ingredients 
    SET stock = stock - :quantite 
    WHERE id = :ingredient
    AND stock >=  :quantite
    

    【讨论】:

      【解决方案2】:

      添加检查约束,以便数据库确保数据完整性,而不是应用程序。

      alter table ingredients add constraint chk_ingredients_stock_gt_0
          check (stock >= 0);
      

      实际上从 MySQL 8.0.16 开始强制执行检查约束。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-07
        • 1970-01-01
        • 1970-01-01
        • 2012-08-09
        • 2017-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多