我正在将对象列表上传到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