简体   繁体   English

使用解码的 json 字符串插入新行

[英]insert a new row using decoded json string

$str is a json object-string from client side $str是来自客户端的 json 对象字符串
keys are column names keys是列名
need to insert a new row using prepared values - ie corresponding key value pairs需要使用准备好的值插入新行 - 即对应的键值对
how can I do - like this:我该怎么办 - 像这样:

$str = {"fname":"lorem","sname":"ipsum","nick":"dolor"};

function btn_send($str){
    global $db;
    $obj = json_decode($str);
    $sq = "insert into members (...keys) values (...prepared_values)";
    $st = $db->prepare($sq);
    $st->execute([...]);
}
<?php


$str = '{"fname":"lorem","sname":"ipsum","nick":"dolor"}';

function btn_send($str){
    global $db;
    $data = json_decode($str,true);
    $column_names = "`". implode("`,`",array_keys($data)) . "`";
    $prepared_chars = implode(",",array_fill(0,count(array_values($data)),'?'));
    $sq = "insert into members ($column_names) values ($prepared_chars)";
    $st = $db->prepare($sq);
    $st->execute(array_values($data));
}

You can make the column names out of the json keys and have those many ?您可以使用 json 键来制作列名,并且有很多? placeholders as much as values for those keys.占位符与这些键的值一样多。 While executing the prepared query, you can just supply the values.在执行准备好的查询时,您可以只提供值。

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

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