[英]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.