PHPを使用してアレイと更新のMySQL

ジョン・アレキサンダー:

私は真剣にPHPを使用してArrayでMySQLデータベースへの更新を渡そうと立ち往生しています。データはから来ているAPIのPHPを使用してアプリを反応します。現在、私は、データベースに反映された結果を取得することができません。

リアクトからアレイ

{"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に遭遇しましたが、私は、しかし、私はこのことについてわからないです、1の整数を返すべき真としてINTVAL使用しています。任意の助けてくれてありがとう。

乾杯、

Barmar:

あなたがしているので、true2番目の引数として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>";
    }
}
?>

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=339484&siteId=1