N
N
nollo2015-09-04 19:25:47
MySQL
nollo, 2015-09-04 19:25:47

How to insert json into mysql?

When adding an array converted to a string to a database, the server crashes. The server is made on Node.js.
Here is an example code:

T[0]=1;
T[1]=2;
T[2]="3";
T[3]=4;
T[4]="5";
T=JSON.stringify(T);
connection.query('INSERT INTO `tasks` (`login`,`description`,`type`,`time`) VALUES ("'+req.body.login+'","'+T+'","'+"3"+'","'+st+'")');

How can this error be corrected?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Prozorov, 2015-09-04
@nollo

0) It is better to frame the SQL query string with double quotes in order to safely use single quotes inside the query to denote text constants.
1) Study the documentation for the module you are using, everything is described in detail and accessible there.
2) Don't insert parameters directly into the request. Never .

var T = [1, 2, '3', 4, 5];
connection.query("INSERT INTO `tasks` SET ?", {
  login: req.body.login,
  description: JSON.stringify(T),
  type: 3,
  time: new Date()
}, function(err) {
  if (err) throw err;
});

UPD : is it even possible
var T = [1, 2, '3', 4, 5];
connection.query("INSERT INTO ?? SET ?", [
  'tasks', 
  {
    login: req.body.login,
    description: JSON.stringify(T),
    type: 3,
    time: new Date()
  }
], function(err) {
  if (err) throw err;
});

O
Oleg, 2015-09-04
@mayken

"'+"3"+'" - maybe there's a bug here!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question