简体   繁体   English

PHP MYSQL使用JSON输入的内容构建动态UPDATE查询

[英]PHP MYSQL Build a dynamic UPDATE query with content thats fed in by JSON

PHP 的PHP

$postdata = json_decode(file_get_contents("php://input"));
$src = $postdata->data;
print_R( $src );

The above prints out 上面打印出来

stdClass Object
(
    [id] => 1
    [first] => Joe
    [middle] => Cornelius
    [last] => Bloggs
)

But what I'm looking to do is build an UPDATE MySQL Query that is dynamic so that if in the event that the data input could be something like the following: 但是我想要做的是构建一个动态的UPDATE MySQL查询,以便在发生数据输入的情况下可以像下面这样:

stdClass Object
    (
        [id] => 1
        [first] => Joe
        [middle] =>
        [last] => Bloggs
    )

Then the MySQL Query would miss out middle from updating. 然后,MySQL查询将错过更新的middle时间。 The MySQL Table rows march the id of the array. MySQL Table行行进数组的id

I have tried to have a go at this but all I can think of doing is an if statement to see if there is a value but thats not looping. 我已经尝试过了,但是我能想到的只是一个if语句,看是否有值,但是那不是循环的。

I was hoping someone would think of a simpler way. 我希望有人会想到一种更简单的方法。

Something like this? 像这样吗

$src = (array) $src;
$sets = array();
$valid_fields = array('first','middle','last');

foreach( $valid_fields as $valid_field )
{
  if(!empty($src[ $valid_field ]))
  {
    $safe_data = some_type_of_validation( $src[ $valid_field ]); // addslashes? mysql_real_escape_string?
    $sets[] = "{$valid_field} = '{$safe_data}'";
  }
}

if(!empty($sets))
{
  $set_clause = implode(',',$sets);
  $sql = "UPDATE table SET {$set_clause} WHERE id = {$id}";
}

Notice that this does not allow you to set a value to an empty string, so if, for example, someone did want to set their middle name to '', this wouldn't work. 请注意,这不允许您将值设置为空字符串,因此,例如,如果某人确实想要将中间名设置为“”,则此操作将无效。

foreach ($src as $field => $value) {
            $list[] = $field.'='."'".mysql_real_escape_string($value)."'";
        }
        $fields = implode(', ', $list);

        $q = $db->query("UPDATE people SET ".$fields." WHERE id = $src[id]");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM