PHP:为可用的$ _POST变量创建SQL查询

时间:2016-02-17 17:14:31

标签: php mysql post

我有这个$ _POST变量:

Array
(
    [phone_1] => 3123213
    [phone_2] => 432423
    [phone_3] => 4234
    [phone_4] => 6456456
    [phone_5] => 7567576
    [phone_6] => 
)

现在我有了这个SQL语句:

UPDATE table_name SET phone_1 = $_POST['phone1'],
phone_2 = $_POST['phone2'], 
phone_3 = $_POST['phone3'], 
phone_4 = $_POST['phone4'], 
phone_5 = $_POST['phone5'], 
phone_6 = $_POST['phone6'] 
WHERE id=$id

我想要实现的是基于$ _POST变量动态构建SQL查询,并且只包含具有post值的那些。所以SQL语句应该是:

UPDATE table_name SET phone_1 = $_POST['phone1'],
    phone_2 = $_POST['phone2'], 
    phone_3 = $_POST['phone3'], 
    phone_4 = $_POST['phone4'], 
    phone_5 = $_POST['phone5']

因为phone_6 post变量是空白的。是的$ _POST键名与表字段名相同。 TIA!

2 个答案:

答案 0 :(得分:3)

你可以用这个:

<?php
$update = "";
foreach($_POST as $key => $value) {
   if(!empty($value)) {
     $update .= $key. "='".$value."',";
   }
}
$update = substr($update,0,-1);
$query = "UPDATE table_name SET ".$update." WHERE id=$id";

?>

答案 1 :(得分:0)

$postVar    = array_filter($_POST);
$update     = implode(', ', array_map(function($v, $k) { return $k."='".$v."'"; }, $postVar, array_keys($postVar)));
$query      = "UPDATE table_name SET ".$update." WHERE id=$id";

通过使用implodearray_map避免循环,这也是更好的方法 http://php.net/manual/en/function.array-map.php