【发布时间】:2020-06-27 02:02:21
【问题描述】:
我在尝试使用 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,但是我不确定这一点。 感谢您的帮助。
干杯,
【问题讨论】:
-
当您解码为关联数组时,您可能应该使用
$users['harassment_val'] -
了解 sql 注入以及准备和绑定查询的重要性
-
或者你可以从
json_decode()调用中删除,true,然后你会得到一个对象数组。 -
奈杰尔·任,做到了!非常感谢。