夏期劇場
夏期劇場

Reputation: 18325

PHP save in MySQL for the Object coming from Javascript "JSON.stringify" via Ajax?

I have an Object from Javascript pass to PHP (via AJAX):

var jsObject = {
    "name": "Michael Divo",
    "age": 27,
    "country": "United States"
};

jsObject_json = JSON.stringify( jsObject );

$.ajax({
    type: "POST",
    dataType: 'json',
    url: "http://www.example.com/myserver.php",
    data: { mydata: jsObject_json },
}) ...

In, myserver.php:

$json = json_decode($_POST["mydata"], true);

Then if i save that $json into the MySQL from this PHP end, it is saved as:

Array

.. in the Database, as that "Array" as a String.


So how do i properly SAVE this JSON into the MySQL please? (So that i can later retrieve it back as a JSON and read.)

Upvotes: 0

Views: 2772

Answers (5)

Gabber
Gabber

Reputation: 7249

try this

$str = $db->prepare("INSERT INTO table (json_array) VALUES (:json_data)");
$str->execute($_POST["mydata"]);

Upvotes: 0

Rohit Choudhary
Rohit Choudhary

Reputation: 2269

As your Database schema is not provided here so assuming that you need to store the string only, in this case don't decode your json as this will turn json string to array. In case of you have schema then you can proceed by decoding this into array and then save elements according to you table schema.

Upvotes: 0

greut
greut

Reputation: 4363

By using json_encode() you can reencode your Array into a JSON that can be stored into a TEXT field in MySQL. Or since, you already have it as a string, leave it as is.

$stmt = $db->prepare("INSERT INTO FOO (mydata) VALUES (:my_data)");
$stmt->execute($_POST);

Upvotes: 0

Sabri Aziri
Sabri Aziri

Reputation: 4184

You dont need to decode it before you store it into db, (store it as pure string), then if you what to get it back(somewhere else in your code) get that string and decode it.

Upvotes: 0

Quentin
Quentin

Reputation: 943217

If you just want to pull it back as JSON, then don't run it through json_decode. Leave it as a string.

Most sensible systems, however, would have a database structure that would allow each of the fields in the JSON submission to be handled separately. Then you would access each field and add it in its own column in the INSERT query. You could then perform queries on the data beyond "Give me all the data" (e.g. WHERE country = 'United States').

$preparedStatement = $db->prepare('INSERT INTO data (name, age, country) VALUES (:name, :age, :country)');
$preparedStatement->execute(json_decode($_POST["mydata"], true));

Upvotes: 3

Related Questions