-1

I'm trying to get post data from postman which is multiple arrays of data but can't seem to get them to go into the database, If I do hard code the array on post it'll go into the database but not dynamically.

index.js

/* POST home page. */
router.post('/', function (req, res) {
    const sql = require('../models/db.js');

    let data = req.param('data');
    console.log(data);

    const sqlstatement = "INSERT INTO Sales (user_id, type, amount) VALUES (?)";

    sql.query(sqlstatement, [data], function (err, res) {

        if(err) {
            console.log("error: ", err);
        }
        else{
            console.log(res.insertId);
        }
    });

    res.send(data);

});

db.js



'user strict';

const mysql = require('mysql');

//local mysql db connection
let connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'api'
});

connection.connect(function(err) {
    if (err) throw err;
});

module.exports = connection;

postman data

[{"key":"data","value":"[[111, 'net', 1234],[111, 'gross', 1234]]\n","description":"","type":"text","enabled":true}]

console error


code: 'ER_BAD_FIELD_ERROR',
  errno: 1054,
  sqlMessage:
   "Unknown column '[[111, 'net', 1234],[111, 'gross', 1234]]' in 'field list'",
  sqlState: '42S22',
  index: 0,
  sql:
   "INSERT INTO Sales (user_id, type, amount) VALUES (`[[111, 'net', 1234],[111, 'gross', 1234]]`)" }
Ancesteral
  • 109
  • 9

2 Answers2

0
const sqlstatement = "INSERT INTO Sales (user_id, type, amount) VALUES (?,?,?)"

You have to put a question mark for every column.

trizin
  • 347
  • 2
  • 13
0

Prepare proper SQL statement

INSERT INTO Sales (user_id, type, amount) VALUES (111, 'net', 1234),(111, 'gross', 1234);
showdev
  • 28,454
  • 37
  • 55
  • 73