[英]Insert Json data into mysql database with json datatype using php
我有從UNITY3d WWWForm到我的php文件的表單數據。 我用json文件類型創建了一個列,現在我想將該字符串存儲在數據庫中。 我還希望id字段是其余數組的鍵。
include('dbconfig.php');
$id= $_POST['ID'];
$servicedate=$_POST['ServiceDate'];
$servicelocation=$_POST['ServiceLocation'];
$mileage=$_POST['Mileage'];
$labor=$_POST['Labor'];
$oilbrand=$_POST['OilBrand'];
$oilprice=$_POST['OilPrice'];
$filterbrand=$_POST['FilterBrand'];
$filterprice=$_POST['FilterPrice'];
$oilfilterpurchaselocation=$_POST['PurchasePlace'];
$arr = array('Service Date' => $servicedate,
'Service Location' => $servicelocation,
'Mileage' => $mileage,
'Labor' => $labor,
'Oil Brand' => $oilbrand,
'Oil Price' => $oilprice,
'Filter Brand' => $filterbrand ,
'Filter Price' => $filterprice ,
'Purchase Place' =>$oilfilterpurchaselocation);
$json= json_encode($id => $arr); //Is this part right?
echo 'Here is our new JSON';
echo $json;
$var= $db->prepare("INSERT into json VALUES(?,?,?,?,?)";
foreach($data as $row)
{
$var->bindParam(1, $row['id']);
$var->bindParam(2, $row['']);
$var->bindParam(3, $row['']);
$var->execute();
}
這是我所需要的嗎? 謝謝!
您的所有數據都以數組$ arr傳遞,您可以簡單地使用此代碼。
$json= json_encode($arr);
不要使用echo檢查print_r($ json)中的json數據;
我昨天看了一下代碼,卻忘記了在插入的值部分添加引號。 當我運行它時,我遇到了另一個錯誤,所以我知道自己正在進步! 事實證明,有人讓我知道這是否正確,我不得不將所有列更改為默認值。 當我將它們全部更改為NULL時,我能夠插入json數據。 如果其他任何人都在為此問題苦苦掙扎,這是您需要的insert命令。
$sql= "INSERT INTO column_name (name of parameter) VALUES ('$json')";
$result = mysqli_query($ms, $sql);
if(!$result)
{
echo' Item Not Inserted! '. mysqli_error($ms);
}
else
{
echo"Item Inserted!";
}
確保您執行json_encode以創建可以放置在數據庫中的json對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.