我正在將對象列表上傳到MySQL。 某些對象不包含相同數量的變量。例如如何在Mysql中將對象屬性設置爲null
Objectt1 {
property1
property 2
}
Objectt2 {
property1
property2
property3
}
Objectt3 {
property1
}
我的問題是,在mysql中的Object3被賦予一個property2和property3而不是NULL。該值取自Object2。我怎樣才能使對象3的propery2和property3爲空? PHP代碼如下:(。我想我明白爲什麼這樣做,因爲變量在循環的先前運行已經isset但我不知道如何解決它)
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if($_SERVER["REQUEST_METHOD"] == "POST") {
require 'connection.php';
uploadstart();
}
function uploadstart() {
global $connect;
$json = $_POST["objectlist"];
//Remove Slashes
if (get_magic_quotes_gpc()){
$json = stripslashes($json);
}
$createworkoutquery = $connect->prepare("INSERT INTO objectTable
(id, prop1, prop2, prop3)
VALUES (?, ?, ?, ?)");
$createworkoutquery->bind_param("ssss", $ID, $prop1, $prop2, $prop3) ;
//convert json object to php associative array
$data = json_decode($json, true);
//Util arrays to create response JSON
$a=array();
$b=array();
// loop through the array
foreach ($data as $row) {
// get the list details
$ID = $row["id"];
$prop1 = $row["prop1"];
if (isset($row["prpop2"])) {
$prop2 = $row["prop2"];
}
if (isset($row["prop3"])) {
$prop3 = $row["prop3"];
}
// execute insert query
$result = $createworkoutquery->execute();
//if insert successful.. plug yes and woid else plug no
if($result){
$b["id"] = $ID;
$b["status"] = 'yes';
array_push($a,$b);
} else {
$b["id"] = $ID;
$b["status"] = 'no';
array_push($a,$b);
}
}
echo json_encode($a);
//close connection
mysqli_close($connect);
}
?>
一些明智的代碼茚這將是一個好主意。它可以幫助我們閱讀代碼,更重要的是,它可以幫助您**調試您的代碼** [快速瀏覽編碼標準](http://www.php-fig.org/psr/psr-2/ )爲了您自己的利益。您可能會被要求在幾周/幾個月內修改此代碼 ,最後您會感謝我。 – RiggsFolly
如果你有很多屬性,並且你期望有很多空值,爲什麼不重構你的表,以便它可以讓你擁有變量屬性?如'id | object_id | property_name | property_value'? –
'get_magic_quotes_gpc()'已被硬編碼以返回'false'好幾年了。除非你在一個非常舊的服務器上,否則你應該能夠安全地刪除它。另外,你的ID是一個字符串? 「ssss」表明它是。 – miken32