Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

PHP How To Store and Read Json Data Via Mysql? - Stack Overflow

Uploaded by

5456nbrkdj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

PHP How To Store and Read Json Data Via Mysql? - Stack Overflow

Uploaded by

5456nbrkdj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

php how to store and read json data via mysql?

Asked 12 years, 5 months ago Modified 3 years, 1 month ago Viewed 51k times

Part of PHP Collective

php how to store and read json data via mysql?

13 mysql_query("INSERT INTO text (data) VALUES (json_encode('id' => $uid,


'value' => yes))");

then, how to update data value? read out the data, then insert it with an
json_encode and decode process, or only easy way update?

[{"id": "1", "value": "yes"}]

then insert another change to [{"id": "1", "value": "yes"},{"id": "2",


"value": "yes"}] ...

Or even if a long long value.

[{"id": "1", "value": "yes"},{"id": "2", "value": "yes"}...{"id": "10000",


"value": "yes"}]

then update another one, change to [{"id": "1", "value": "yes"},{"id": "2",
"value": "yes"}...{"id": "10000", "value": "yes"},{"id": "10001", "value":
"yes"}]

I wanna to ask, how to do this mysql query processing more wiser and efficiently?
Thanks for more suggestion.

php mysql json insert

Share Improve this question Follow asked Sep 29, 2011 at 19:09
fish man
2,696 21 54 94
:
Report this ad

Sorted by:
4 Answers Highest score (default)

Technically, you are going the wrong way with that. MySQL is used to store each of
your ID/VALUE seperately. For the sake of NOT changing your code we'll look at
24 your solution first but then i'll explain the "better" way of doing it.

First, you need to make your JSON as a variable, not part of your SQL:

mysql_query("INSERT INTO text (data) VALUES


(".mysql_real_escape_string(array(json_encode('id' => $uid, 'value' =>
'yes'))).")");

instead of

mysql_query("INSERT INTO text (data) VALUES (json_encode('id' => $uid,


'value' => yes))");

This first part will allow you to at least instead the data correctly into mysql. I am
ASSUMING your table has an ID and that you will be using it to update or
delete

When you retrieve your data, you can json_decode the $row['data'] to get your
data back from the row and work with it. To update it, just do:

mysql_query("UPDATE text SET data =


"'.mysql_real_escape_string(json_encode($myJsonToBeData)).'" WHERE rowid =
'.$myrowid)

Now, for the RIGHT way to do this:


:
The right way to do this would be to have these fields into your table: ID, JSONID,
JSONVALUE and use this SQL instead:

SELECT * FROM text WHERE id = $rowid


INSERT INTO text VALUES(NULL, $jsonid, $jsonvalue)
UPDATE text SET jsonid = $jsonid, jsondata = $jsondata

This is pretty basic, but it will allow you to have any number of entries in your
database that make it searchable, indexed, sortable, queryable, etc...

Share edited Aug 16, 2020 at 12:58 answered Sep 29, 2011 at 19:21
Improve this answer Lamanus Mathieu Dumoulin
13.2k 4 21 48 12.2k 7 44 71
Follow

1 I believe there's an extra single quote in your first code example – CervEd Feb 21,
2014 at 19:55

You can do this more efficiently by NOT storing JSON in a single field but by
creating a proper MySQL table with the JSON object's property names as field
3 names.

Storing a text-string encoded representation of your data in a database completely


destroys the point of using databases in the first place.

Share Improve this answer Follow answered Sep 29, 2011 at 19:18
daiscog
11.7k 8 51 62

MongoDb uses a binary JSON storage format. So I'd have to disagree with your
second point that storing data in JSON is a bad idea. For MySQL (and other sql
contagions), your point is valid. – SSH This Jan 4, 2014 at 20:35

1 The question (and my answer) is specifically about MySQL, and storing data encoded
as a JSON string. Furthermore, as you said yourself, MongoDb stores "JSON" as
binary objects, not as JSON strings, so storing "JSON" in MongoDb is NOT storing
data encoded as a string (which is still bad practice and breaks database
normalisation). – daiscog Jan 6, 2014 at 13:06

i will disagree what if i don't know how many fields are going to be there? therefore
best best would be stave all json. – Danish Aug 25, 2018 at 2:38

is there any example of saving JSON object in mysql? how can I do that?
– Kamal Panhwar Jan 23, 2019 at 5:29
:
Most scenarios are not black and white, and this is absolutely one of them. You should
not store array structure in a single field IF each key-value pair would be beneficial, or
even avoid painful usage and management, from being a separate row. E.g. more are
added/removed often. However, a Json object in a single field most certainly has it's
place when the scenario is right. It avoids a potentially pointless table just to store a
pairing, as then you have a new table with an ID and value column. Symfony user roles
is a good example where a Json field is suitable usage. – James Jul 5, 2019 at 2:22

Yes but....WordPress stores a lot of its data as encoded JSON strings, such as the
user capabilities. Storing an array as a discrete bit of data takes away having to do
3 multiple reads on the database and allows you to get a lot of data on one read. If
you never see the need to SELECT the individual parts of the JSON string I don't
see why it isn't acceptable to do it this way. MySQL must think so too because it
has functions to allow a SELECT on the individual fields within a JSON string if you
so desired (see MySQL EXPLAIN keyword). But I do agree if you were going to do a
lot of SELECTs on a field it should have one of its own. It all depends on how you
are going to use the data.

Share Improve this answer Follow answered Jun 3, 2013 at 1:43


KoZm0kNoT
482 6 9

1 Wordpress doesn't store lots of data as json strings, he uses the internal
serialize/unserialize mechanism :) – Mathieu Dumoulin Feb 21, 2014 at 20:21

1 @Mathieu - I said it was "encoded JSON" which means using searialize/unserialize.


Take a look at the EXPLAIN keyword in MySQL. – KoZm0kNoT Dec 21, 2014 at 13:44

Assuming you want to store the JSON string as a text or varchar datatype in
MySQL, you can simply just escape the JSON string like so:
1
Storing

$object = new stdClass();


$object->key_a = "Value A";
$object->key_b = "Value B";

$storable_json_string = trim( addslashes( json_encode( $object ) ) );

// `$storable_json_string` contains an ugly invalid JSON


mysqli_query( "INSERT INTO table_a (column_a) VALUES
('{$storable_json_string}')" );
:
Reading

// read from the database


$result = mysqli_query( "SELECT column_a FROM table_a" );
$row = $result->fetch_object();

// makeover the ugly invalid JSON into a machine readable valid JSON
$valid_json_string = substr( stripslashes( $row->column_a ), 1, -1 );

// makes the JSON as a PHP object


$readable_json_object = json_decode( $valid_json_string );

echo $readable_json_object->key_a; // Value A

This could be not that secure but at least these should give you some stepping
stones.

Share Improve this answer Follow answered Jan 8, 2021 at 18:37


Abel Callejo
14k 10 70 90
:

You might also like