DWQA QuestionsCategory: ProgramHow to store JSON data directly into MySQL database in PHP?
Iosdev asked 1 month ago

Using PHPjson_encodeAfter that, you can directly save the data in MySQL and report an error. Google did not find a proper solution. How can I handle it so that the data in JSON format can be saved in MySQL
Code:
$imgs_str = json_encode($imgs_array);
$imgs_str = addslashes($imgs_str);
$update_query = "update
articleset imageList = $imgs_str where id = $targetid";

4 Answers
Best Answer
cevin answered 1 month ago

The JSON encoded data is as follows:

{"key":"value"}

So SQL is like this:

insert into `table` (`field`) values ("{"key":"value"}")

So there was a mistake
Full code:

$data = json_encode($array);

// filtration
$data = addslashes($data);

// warehousing
$db->insert($table_name,array(
    'field' => $data,
));
felix021 replied 1 month ago

Change to this: $update_query = “update article set Imagelist = ‘$img_str’ where id = ‘$targetid'”

felix021 replied 1 month ago

In general, it is not recommended to use addslashes when escaping SQL statements. The best way is to use real estate string in MySQL / mysqli library

Zi Ting Wang replied 1 month ago

PDO:: quote should be corresponding to MySQL ﹣ real ﹣ escape ﹣ string

thenbsp answered 1 month ago

PHP has a serialize function. You should check the documentation for this problem.

keroppi answered 1 month ago

The input is a bit wrong. JSON in PHP is also generated by JSON encode (I didn’t say ha when I combined it). Use the serialize function. Save the array directly.

Sell your underwear and go online answered 1 month ago

There is no need to store JSON in MySQL
As said by @ Kevin,

$data = json_encode($array);

// filtration
$data = addslashes($data);

// warehousing
$db->insert($table_name,array(
    'field' => $data,
));

In fact, I have done a useless work, that is, JSON encode ($data);