PHP:为可用的$ _POST变量创建SQL查询 [英] PHP: Create SQL query for available $_POST variable

查看:227
本文介绍了PHP:为可用的$ _POST变量创建SQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个$ _POST变量:

I have this $_POST Variable:

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

现在我有以下SQL语句:

Now I have this SQL statement:

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查询.因此,SQL语句应为:

What I want to achieve is to dynamically build the SQL query based from the $_POST variable and only include those that have a post value. So the SQL statement should be:

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!

because phone_6 post variable is blank. And yes the $_POST key names is the same as the table field names. TIA!

推荐答案

您可以使用:

<?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";

?>

这篇关于PHP:为可用的$ _POST变量创建SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆