Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

php - insert a new row using decoded json string

$str is a json object-string from client side
keys are column names
need to insert a new row using prepared values - i.e. 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([...]);
}
question from:https://stackoverflow.com/questions/65839655/insert-a-new-row-using-decoded-json-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
<?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 ? placeholders as much as values for those keys. While executing the prepared query, you can just supply the values.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...