mysql 如何更新数据库字段为空,如何更新一个或多个字段而忽略mysql数据库中的空字段?...

i am seeking help on ignoring null values for updating the mysql database:-

$cst = $_POST['custname'];

$a = $_POST['tel'];

$b = $_POST['fax'];

$c = $_POST['email'];

$sql = mysql_query("UPDATE contacts SET TEL = '$a', FAX = '$b', EMAIL = '$c'

WHERE Cust_Name = '$cst' ");

how do i incorporate an option where the user can only select one or all fields for updation.

i tried using the following code based on responses received but it does the same thing. overwrites the existing data with the blank ones.

$upd = mysql_query("UPDATE custcomm_T SET

Telephone = ".(is_null($a)?'Telephone':"'$a'").",

Fax = ".(is_null($b)?'Fax':"'$b'").",

Mobile = ".(is_null($c)?'Mobile':"'$c'").",

EMail = ".(is_null($d)?'EMail':"'$d'").",

trlicense = ".(is_null($e)?'trlicense':"'$e'").",

trlicexp = ".(is_null($f)?'trlicexp':"'$f'")."

WHERE Cust_Name_VC = '$g' ") or die(mysql_error());

解决方案

Firstly remember to escape any strings coming to you via POST, GET, or REQUEST (read up on SQL injection attacks if you're unsure why).

Something like this might work:

$semaphore = false;

$query = "UPDATE contacts SET ";

$fields = array('tel','fax','email');

foreach ($fields as $field) {

if (isset($_POST[$field]) and !empty($_POST[$field]) {

$var = mysql_real_escape_string($_POST[$field]);

$query .= uppercase($field) . " = '$var'";

$semaphore = true;

}

}

if ($semaphore) {

$query .= " WHERE Cust_Name = '$cst'";

mysql_query($query);

}

NB: Do not ever simply loop through your $_POST array to create a SQL statement. An opponent can add extra POST fields and possibly cause mischief. Looping through a user input array can also lead to an injection vector: the field names need to be added to the statement, meaning they're a potential vector. Standard injection prevention techniques (prepared statement parameters, driver-provided quoting functions) won't work for identifiers. Instead, use a whitelist of fields to set, and loop over the whitelist or pass the input array through the whitelist.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值