I'm serializing a form and sending with jQuery AJAX the data to an express route:
The object sent as arrobj
is for example:
{
col1: [ 'one', 'two', 'three' ],
col2: [ 'foo', 'bar', 'baz' ]
}
In the route i have a function that creates a parametrized query string as follows:
function create_insert_SQL(obj, table, returnid) {
// Loop through OBJ and extract column names
var cols = ''; // Store column names
var params = ''; // Store Parameter references eg. $1, $2 etc
var count = 1;
for(var p in obj) {
cols += p + ",";
params += "$" + count + ",";
count++;
};
var strSQL = "INSERT INTO " + table + " (";
strSQL += cols.substr(0, cols.length - 1);
strSQL += ') VALUES (';
strSQL += params.substr(0, params.length - 1)
strSQL += ') returning ' + returnid + ' as id';
return strSQL;
}
This will return insert into mytable (col1,col2) values ($1, $2);
After the query string is created I run the insert query in node-postgres passing the object:
db.query(SQL, arrobj, function (err, result) {
if (err) {
res.send(err)
} else {
res.send(result.rows[0].id.toString()) // return the inserted value
}
});
For single values in every key everything works fine and the data is inserted in the table correctly.
How can I make the insert query run for every value of the keys?
Example:
insert into table (col1, col2) values ('one', 'foo');
insert into table (col1, col2) values ('two', 'bar');
insert into table (col1, col2) values ('three', 'baz');