gpt4 book ai didi

php - 如何在Mysql中将对象属性设置为null

转载 作者:行者123 更新时间:2023-11-29 07:13:36 27 4
gpt4 key购买 nike

我正在将对象列表上传到 MySQL。某些对象不包含相同数量的变量。例如

Objectt1 {
property1
property 2
}

Objectt2 {
property1
property2
property3
}

Objectt3 {
property1
}

我的问题是mysql中的Object3被赋予了property2和property3而不是NULL。该值是从 Object2 中获取的。如何使对象 3 的 property2 和 property3 为空? php代码如下:(我想我明白为什么这样做,因为该变量已经在之前的循环运行中设置了。但我不知道如何修复它。)

<?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);

}
?>

最佳答案

在每次迭代时将 null 分配给缺失的属性,以便以前的值不会绑定(bind)到查询:

foreach($data as $row){
$ID = $row['id'];
$prop1 = isset($row['prop1'])? $row['prop1']: null;
$prop2 = isset($row['prop2'])? $row['prop2']: null;
$prop3 = isset($row['prop3'])? $row['prop3']: null;

$result = $createworkoutquery->execute();
...
}

关于php - 如何在Mysql中将对象属性设置为null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38731765/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com