【问题标题】:Update MySQL with an Array using PHP使用 PHP 用数组更新 MySQL
【发布时间】: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,然后你会得到一个对象数组。
  • 奈杰尔·任,做到了!非常感谢。

标签: php mysql arrays foreach


【解决方案1】:

由于您将true 作为json_decode() 的第二个参数,因此您得到的是关联数组,而不是对象。删除该参数,以便您可以使用$users-&gt;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>";
    }
}
?>

【讨论】:

  • 谢谢,尝试解码关联数组是个问题。
猜你喜欢
  • 1970-01-01
  • 2011-06-04
  • 2020-05-16
  • 2013-03-08
  • 2014-01-04
  • 2016-08-01
  • 1970-01-01
  • 2016-08-07
  • 1970-01-01
相关资源
最近更新 更多