[英]Update MySQL with an Array using PHP
我在尝试使用 PHP 将更新传递到带有数组的 MySQL 数据库时遇到了严重的困难。 数据来自使用 PHP 作为 API 的 React 应用程序。 目前我无法得到反映在数据库中的结果。
来自 React 的数组
{"updateArray":
[{"user_id":"1000005","harassment_val":true,"safety_val":null},
{"user_id":"1000006","harassment_val":1,"safety_val":null},
{"user_id":"1000007","harassment_val":0,"safety_val":null},
{"user_id":"1000008","harassment_val":0,"safety_val":null},
{"user_id":"1000009","harassment_val":0,"safety_val":null,},
{"user_id":"1000010","harassment_val":1,"safety_val":1},
{"user_id":"1000011","harassment_val":0,"safety_val":null},
{"user_id":"1000012","harassment_val":0,"safety_val":null}]
}
当前 PHP 代码
<?php include 'DBConfig.php';
$con = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$update_array = $obj['updateArray'];
// $update_array is array obj from app
// $content is field harassment_val in array
// $id is user_id field array to be used as key
// users, name of table to be updated
// harassment_val is field in table to be updated
// user_id is field in table to be used as key
foreach ($update_array as $key => $users) {
$content = intval($users->harassment_val);
$id = intval($users->user_id);
$sql = "UPDATE users SET harassment_val='$content' WHERE user_id='$id'";
$result = mysqli_query($con,$sql);
}
?>
我遇到过 mysqli_real_escape_string 但我使用 intval 作为 true 应该返回整数 1,但是我不确定这一点。 谢谢你的帮助。
干杯,
由于您将true
作为json_decode()
的第二个参数,您将获得关联数组,而不是对象。 删除该参数,以便您可以使用$users->user_id
。
那么你应该使用准备好的语句而不是替换变量。
<?php include 'DBConfig.php';
$con = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
$json = file_get_contents('php://input');
$obj = json_decode($json);
$update_array = $obj['updateArray'];
$sql = "UPDATE users SET harassment_val=? WHERE user_id=?";
$stmt = $con->prepare($sql);
$stmt->bind_param("ii", $content, $id);
foreach ($update_array as $key => $users) {
$content = $users->harassment_val;
$id = $users->user_id;
$result = $stmt->execute();
if (!$result) {
echo "Error: $stmt->error <br>";
}
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.