簡體   English   中英

使用 PHP 使用數組更新 MySQL

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM