13

I am gathering data from a webpage visitor and putting it into a JavaScript object I create. But later I want to be able to reference the data they entered.

I have access to a MySQL database, so is there a way for me to store this object there?

I want to try and keep it in the object format instead of breaking it up into its separate parts.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Steve H
  • 151
  • 1
  • 1
  • 6

5 Answers5

18

Store a JSON.stringified version of your object in the database, then JSON.parse it when you want the object back again. It would look something like this:

var myObj = {some: data, other: stuff};
var myObjString = JSON.stringify(myObj);
// store string in mySQL database here

// load string from database
var myJSONString = //mySQL database call
var myLoadedObj = JSON.parse(myJSONString);
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
10

No, you can't, at least not as it is.

You might be able serialise it to a string. If it consists entirely of arrays, simple objects, and the other data types supported by the JSON format (which it probably will do if it is user supplied data (the main exception being if binary files are uploaded)), then you could use a JSON serializer to do so. Modern browsers provide the JSON object for this purpose and json2.js will polyfill for older browsers. You could then store the string in the database.

Not breaking it into separate parts does throw away the many of the advantages of using a relational database though (i.e. the relationships and the ability to perform useful searches).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

Just store it as a JSON object in a field using the varchar or text data type.

Adrian J. Moreno
  • 14,350
  • 1
  • 37
  • 44
0

Take a look at JSON. You can use something like jQuery to serialize form data and send it off to the server. Also you could just use plain old forms, and process input on the server side.

kevin628
  • 3,458
  • 3
  • 30
  • 44
0

Yes Actually It can be done.

con.connect(function(err){
  var sql = "INSERT INTO books SET ?";  //books -- <tablename>
  if(err) console.dir("Error: "+err.message);
  var values = {
    "bname": "Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future",
    "author": "Elon Musk",
    "genre": "Technology",
    "bookcount": "5"
  };
  con.query(sql, [values], function(err, result){
    if (err) throw err;
    else console.dir("Successfully inserted the row in table.");
    console.log(result);
  });
}); 

But, along with this you have to satisfy these points,

  • value should be object i.e., value={ "name":"property" }
  • It should not be an array i.e., values = [{}, {}]
  • Imp. - It should not have primary id column.

Hope it helps.

Abhinav Kumar
  • 2,883
  • 1
  • 17
  • 30
Hari Kishore
  • 2,201
  • 2
  • 19
  • 28