0

I tried to pass JSON string into MySQL DB with PHP. But into DB table inserts "Array", and in the debug.txt file inserts normal string.

    require("conf/mysql.php");

if(!empty($_POST)){
    $json = $_REQUEST;
    $obj = $json;
    $sql = "INSERT INTO server_info (`data`) VALUES ('".mysqli_real_escape_string($obj)."')";
    file_put_contents("debug.txt", $obj);
    if (!$result = $mysqli->query($sql)) file_put_contents("db.log", "DB failure while executing query\n$mysqli->error\n$sql");
}
else
    die("Illegal method!");

Debug.txt

{"Map":"gm_metro_nekrasovskaya_line_v3","PlayerCount":1.0,"Wagons":0.0,"MaxWagons":6.0,"MaxPlayers":15.0,"ServerName":"Verona General Metrostroi","Players":[{"SteamID":"STEAM_0:1:57045033","Nick":"thescs","Rank":"superadmin","Time":8776.0,"Position":"Депо"}]}

Whats wrong?

0

2 Answers 2

0

$_REQUEST is an array. mysqli_real_escape_STRING takes a string. file_put_contents takes a string or an array (s. documentation). The file_put_contents function converts the array automatically to a readable string version of the array. mysqli_real_escape_string don't do this.

Solution: convert the array to a string using json_encode (Documentation)

Sign up to request clarification or add additional context in comments.

Comments

0

use json_encode to convert JSON to string in php
$sql = "INSERT INTO server_info (data) VALUES ('".mysqli_real_escape_string($conn,json_encode($obj))."')";

Make sure the field 'data' can store the entire JSON string e.g: TEXT or LONGTEXT as it data type

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.