gpt4 book ai didi

php - sql UPDATE row::如果输入为空则保留当前值

转载 作者:搜寻专家 更新时间:2023-10-30 23:15:29 27 4
gpt4 key购买 nike

我是新手,我不确定这是一个 php 问题还是一个 sql,但我有一个没有必填字段的表单,当提交它时,它会更新数据库行中的列。目前,当提交表单时,如果输入留空,它会用空白空间更新相应的列并删除曾经存在的值。我想弄清楚的是如何在提交表单时做到这一点,如果输入值为空,它不会更新数据库列。

if ( isset($_POST['submit']) ) {
$user = $_SESSION['user_name'];
$signature = $mysqli->real_escape_string($_POST['signature']);
$skype = $mysqli->real_escape_string($_POST['skype']);
$facebook = $mysqli->real_escape_string($_POST['facebook']);

$insert = $mysqli->query("
UPDATE users
SET u_signature='$signature', u_skype='$skype', u_facebook='$facebook'
WHERE u_name='$user'
") or die ($mysqli->error);

最佳答案

<?php
if ( isset($_POST['submit']) ) {

$user = $_SESSION['user_name'];
$signature = mysql_real_escape_string($_POST['signature']);
$skype = mysql_real_escape_string($_POST['skype']);
$facebook = mysql_real_escape_string($_POST['facebook']);
if(!empty($signature)){
$update_fields[] = "u_signature='$signature'";
}
if(!empty($skype)){
$update_fields[] = "u_skype='$skype'";
}
if(!empty($facebook)){
$update_fields[] = "u_facebook='$facebook'";
}
if(count($update_fields) > 0){
$nonempty_fields = implode(", ", $update_fields);
$insert = mysql_query("
UPDATE users
SET $nonempty_fields
WHERE u_name='$user'
") or die(mysql_error());
}
else{
echo "must not update the db because all required fields are empty";
}

}
?>

关于php - sql UPDATE row::如果输入为空则保留当前值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14677362/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com