doujunchi1238 2018-07-27 08:03
浏览 117
已采纳

如果参数有值,则更新记录 - SQL,PHP

My current code updates all values, and if there is an empty parameter it updates the corresponding field on the table to null. I want to update only the fields that have a value.

This is my code:

$sql = "
    UPDATE drinks SET
    name        = :name,          // Mojito -> Update it
    description = :description,   // Lorem ipsum.. -> Update it
    glass_id    = :glass_id,      // NULL -> do not update
    video_url   = :video_url      // NULL -> do not update
    WHERE id = '$drinkId'
";

try {
    $db = new db();
    $db = $db->connect();
    $stmt = $db->prepare($sql);
    $stmt->bindParam(':name', $drinkName);
    $stmt->bindParam(':description', $description);   
    $stmt->bindParam(':glass_id', $glassId);
    $stmt->bindParam(':video_url', $videoUrl);
    $stmt->execute();



// Close databse
$db = null;


} catch(PDOException $e) {
    echo $e;
}
  • 写回答

1条回答 默认 最新

  • dongsha2792 2018-07-27 08:10
    关注

    you don't want to update those 2 fields when they are empty.

    this code check if a field is null and only when it is not null it will add the field to the query, also the same for binding the value.

    $sql = 'UPDATE drinks SET';
    $sql = sql . 'name = :name,';
    $sql = sql . 'description = :description';
    
    if (!is_null($glassId))
        $sql = sql . ',glass_id = :glass_id';
    
    if (!is_null($videoUrl))
        $sql = sql . ',video_url = :video_url';
    
    $sql = sql . ' WHERE id = :drinkId';
    
    try {
        $db = new db();
        $db = $db->connect();
        $stmt = $db->prepare($sql);
        $stmt->bindParam(':name', $drinkName);
        $stmt->bindParam(':description', $description);
        $stmt->bindParam(':drinkId', $drinkId);
    
        if (!is_null($glassId))
        $stmt->bindParam(':glass_id', $glassId);
    
        if (!is_null($videoUrl))
        $stmt->bindParam(':video_url', $videoUrl);
    
        $stmt->execute();
    
        // Close databse
        $db = null;
    
    
    } catch(PDOException $e) {
        echo $e;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址