$aaa={"editdata":[{"id":"8","pwd":"123123d","table":"Test1"},{"id":"1","name":"001","table":"list2"}]};
$bbb=json_decode($aaa,ture);
大家好
我想做一個網頁修改資料後,直接更新mysql database.
我的json data 在上面,我的範例:
兩筆json要修改的"欄位"跟"table"都不一樣
因為每筆資料"欄位"跟"table"的值是浮動的....所以不知道該怎麼正確地在PHP裡面識別?
並且填到update指令裡面,讓SQL更新資料
謝謝大大....
foreach($bbb as $key => $value){
foreach($value as $key1 => $value1){
foreach($value1 as $key2 => $value2){
$sql = "UPDATE .....
}
}
}
燒~~~燒燒燒,剛寫完的
<?php
$aaa='{"editdata":[{"id":"8","pwd":"123123d","table":"Test1"},{"id":"1","name":"001","table":"list2"}]}';
$bbb=json_decode($aaa,true);
foreach($bbb["editdata"] as $v){
$ak = array_keys($v);
$sql = "UPDATE {$v["table"]} SET {$ak[1]} = '{$v[$ak[1]]}' WHERE {$ak[0]} = '{$v[$ak[0]]}';";
echo $sql."<BR>";
// $sql看你如何執行
// $pdo->prepare($sql);
}
?>
輸出
UPDATE Test1 SET pwd = '123123d' WHERE id = '8';
UPDATE list2 SET name = '001' WHERE id = '1';
如果我陣列0跟陣列1長度不同 那該怎麼處裡呢? 謝謝{"editdata":[{"id":"8","name":"111","love":"cake","pwd":"123123d","table":"Test1"},{"id":"1","name":"001","table":"list2"}]}
對$ak = array_keys($v)再foreacha 次,第一個當KEY的排除掉
講的好簡單,真的也不難,多用一個implode而已
<?php
$aaa='{"editdata":[{"id":"8","name":"111","love":"cake","pwd":"123123d","table":"Test1"},{"id":"1","name":"001","table":"list2"}]}';
$bbb=json_decode($aaa,true);
foreach($bbb["editdata"] as $v){
$ak = array_keys($v);
$akl = count($ak);
$kvs = array();
foreach(array_slice($ak,1,$akl-2) as $fk){ //去頭pk 去尾table
array_push($kvs, "{$fk} = '{$v[$fk]}'");
}
$kvstring = implode(',',$kvs);
$vsql = "UPDATE {$v["table"]} SET {$kvstring} WHERE {$ak[0]} = '{$v[$ak[0]]}'<BR>";
echo $vsql;
}
?>
輸出
UPDATE Test1 SET name = '111',love = 'cake',pwd = '123123d' WHERE id = '8'
UPDATE list2 SET name = '001' WHERE id = '1'
大概這樣吧,還沒測試
foreach($bbb['editdata'] as $rowData) {
$id=$rowData['id'];
unset($rowData['id']);
$keys=array_keys($rowData);
$keysStr=implode(', ', array_map(function($x){
return "`$x`=:?";
}, $keys));
$vals=array_values($rowData);
$vals[]=$id;
$sql="UPDATE `tb_name` SET $keysStr WHERE id=:?";
$stmt=$pdo->prepare($sql);
$pdo->execute($vals); //(其實應該還要依據資料型態來 bindValue 才對)
}
因為每筆資料"欄位"跟"table"的值是浮動的....所以不知道該怎麼正確地在PHP裡面識別?
並且填到update指令裡面,讓SQL更新資料
我覺得這類多筆資料一次更新的動成,最好由資料庫的procedure來執行,前台只要傳一個json參數進去,資料庫來解析json並做出相對應的多筆更新。
你好 謝謝你的回應 ,有範例可參考嗎,非常謝謝
https://mariadb.com/kb/en/json-functions/
您看看看那些函數,再試著去理解,
因為那些函數能解析json,就能直接抽出【欄位】和【值】了。