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]]`)" }
const sqlstatement = "INSERT INTO Sales (user_id, type, amount) VALUES (?,?,?)"
You have to put a question mark for every column.
Prepare proper SQL statement
INSERT INTO Sales (user_id, type, amount) VALUES (111, 'net', 1234),(111, 'gross', 1234);
Related
I am trying to use Promise and Then. I try to input the data for two foreign keys' table and get the insertId for the table that contains the sole two constaints. I think I did it orderly in the code, but I don't know why it still show the insertId still 0. Here is my code:
const connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'password',
database: 'filmgogoApplicants'
});
app.post('/submit',(req, res) => {
let sql0 ="INSERT INTO applicantsInfo SET ?";
let sql11 = "INSERT INTO proSkillInfo SET ?";
let sql22 = "INSERT INTO applicant SET ?";
let applicantInfoData = {
chineseName: req.body.chineseName,
englishName: req.body.englishName,
cellPhone: req.body.cellPhone,
emailAddress: req.body.emailAddress
}
let proSkillInfoData = {
photography: 1,
design: 1,
writing: 1
}
const myPromise = new Promise((resolve, reject) => {
var applicantInfoInsertId = 0;
var proSkillInfoInsertId = 0;
if(applicantInfoInsertId == 0 && proSkillInfoInsertId == 0) {
let query0 = connection.query(sql0, applicantInfoData,(err, results, ) =>{
if(err) throw err;
console.log("applicantInfoData is stored for sql");
applicantInfoInsertId = results.insertId;
console.log(applicantInfoInsertId);
})
let query1 = connection.query(sql11, proSkillInfoData,(err, results) =>{
if(err) throw err;
console.log("proSkillInfo is stored for sql");
proSkillInfoInsertId = results.insertId;
console.log(proSkillInfoInsertId);
})
let applicantData = {
applicantsInfoID: proSkillInfoInsertId,
proSkillID: applicantInfoInsertId
}
resolve (applicantData);
} else {
reject(error);
}
});
myPromise.then((message) => {
let query2 = connection.query(sql22, message,(err, results) =>{
if(err) throw err;
console.log("applicant data is stored for sql");
res.redirect('/success');
})
})
})
the error info is below
errno: 1452,
sqlMessage: 'Cannot add or update a child row: a foreign key constraint fails (filmgogoApplicants.applicant, CONSTRAINT proSkillID FOREIGN KEY (proSkillID) REFERENCES proSkillInfo (proSkillID))',
sqlState: '23000',
index: 0,
sql: 'INSERT INTO applicant SET applicantsInfoID = 0, proSkillID = 0'
}
I think I already set applicantsInfoID and proSkillID to the insertId. How come they are still 0??
A picture of MySQL table
For async work with database I would suggest an ORM like Sequelize in order to manage the connection and data transfer using models or Bluebird which creates some promises that waits for responses from the database. Your error comes because you're not handling properly the insertion for you tables relationship. Using the ORM would help alot
const mysql = require('mysql');
const dbCon = mysql.createConnection({
host: "localhost",
user: "mainUser",
password: "pa55",
database: "testDB"
});
dbCon.connect(function (err) {
if (err) throw err;
console.log("Connected to DB");
});
When I run it, I see the "Connected to DB" log but the program never finishes or exits, like it's waiting for something.
Let's try to get the code below and save this to 'dbConnect.js' file and then run node-command:
> node dbConnect.js
you will see the result.
const mysql = require('mysql');
const dbCon = mysql.createConnection({
host: "localhost",
user: "mainUser",
password: "pa55",
database: "testDB"
});
dbCon.connect(function(err) {
if (err) {
return console.log(err.message);
}
console.log('Connected to the MySQL server.');
});
let dbCreateQuery = `
create table if not exists users(
id int primary key auto_increment,
first_name varchar(255)not null,
last_name varchar(255)not null);
`;
let dbInsertQuery = `
insert into users (first_name, last_name)
values ('john', 'smith');
insert into users (first_name, last_name)
values ('jane', 'smith');
`;
let dbSelectQuery = `
select *
from users
`;
//test of create query execute
dbCon.query(
dbCreateQuery,
function(err, results, fields) {
if (err) {
console.log(err.message); //execution error
}
else {
console.log('Table "users" has been created';
}
});
//test of insert query execute
dbCon.query(
dbInsertQuery,
function(err, results, fields) {
if (err) {
console.log(err.message); //execution error
}
else {
console.log('Table "users" has been filled';
}
});
//test of select query execute
dbCon.query(
dbSelectQuery,
function(err, results, fields) {
if (err) {
console.log(err.message);
}
else {
console.log('Data rows from table "users" has been extracted';
console.log(results); // data rows
console.log(fields); // meta of fields
}
});
/*
Also, recommended use 'end()' method for closing connection to database after running operations.
*/
dbCon.end(function(err) {
if (err) {
return console.log(err.message);
}
console.log('Close the MySQL server connection.');
});
/*
Then use 'destroy()' method for close connection immediately, it's
guarantees that no more callbacks or events will be triggered for the connection,
i.e. method does not take any callback argument like the end() method.
*/
dbCon.destroy();
I have created a normal registration form with following fields:
name,email,dob,gender,password
i am using express.js and within post route i access it via
req.body.(param)
console.log(req.body) shows all params.
Now i have mysql table with same columns as mentioned before. If i do insert with plain strings (eg: abcs) it works i.e. value is inserted into mysql table. Also the email in form is username in db.
When I try inserting all the fields it shows error :( unknown username field ). username varchar(50) is its definition. in the logs i see password field's input is surrounded with single quotes but as for email it becomes: ('user#mail'.'com'). I also used knex, alternate ways as mentioned in mysql docs and got same error(unknown username) .
Can someone tell me how should i store email in mysql db via nodejs+express
db.js
var mysql = require('mysql');
// setup mysql
var dbcon = mysql.createConnection({
host: 'localhost',
database: 'test',
user: 'flip',
password: 'flop'
});
dbcon.connect(function (err) {
if (err) throw err;
console.log("Connected to db");
});
module.exports = dbcon;
routes/index.js:
var dbcon = require('../db');
.
.
router.post('/signup', function (req, res) {
console.log(req.body);
/* knex('users').insert( {
user_id: 1,
password: req.body.su_password,
u_firstname: req.body.su_firstname,
u_lastname: req.body.su_lastname,
u_gender: req.body.su_gender,
u_dob: req.body.su_date,
}).then(function(arg){
console.log(arg);
});
*/
dbcon.connect(function (err) {
var sqlv = {
user_id: 1,
password: req.body.su_password,
u_firstname: req.body.su_firstname,
u_lastname: req.body.su_lastname,
u_gender: req.body.su_gender,
u_dob: req.body.su_date
};
/*var sql = "insert into `users` values (?,??,??,??,??,??,??);";
var sqlv = [1,req.body.su_email, req.body.su_password, req.body.su_firstname, req.body.su_lastname, req.body.su_gender, req.body.su_date];
sql = mysql.format(sql,sqlv);
*/
//var sql ="insert into usertmp (`username`,`password`) values ('"+req.body.su_email+"','"+req.body.su_password+"');";
dbcon.query("insert into users values ? ;", sqlv, function (err, result) {
if (err) {
console.log(err);
throw err;
}
console.log("inserted into users " + result);
});
});
res.redirect('/');
});
console.log(req.body) in routes/index.js:
{ su_firstname: 'user',
su_lastname: 'virus',
su_email: 'user#mail.com',
su_gender: 'm',
su_date: '1999-01-01',
su_password: 'passowrd00' }
Error(for current example):
{ Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right syntax to use near 'user_id = 1, password = 'passowrd00', u_firstname = 'user', u_lastname =' at line 1
Error(for insert using actual sql query with single quotes around each value):
Unhandled rejection Error: ER_BAD_FIELD_ERROR: Unknown column 'username'
in 'field list'
I figured it out !
It wasn't nodejs/expresjs mistake it was from the database.
In the database i had used triggers and forgot to use NEW/OLD prefixes.
I want to check if some date exist in a table, if not I want to insert it. I have done this in other project and there it works but now i don't know why it doesn't work.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '',
user : '',
password : '',
database : ''
});
[..]
connection.query('SELECT id FROM users [...]', function(err, results) {
if (err) {
throw err;
} else if (results.length==1) {
callback(null, results[0].id);
} else {
console.log('before insert');
connection.query('INSERT INTO users SET ?', user, function(err, result) {
console.log('insert');
if (err) throw err;
});
}
});
The query with INSERT doesn't work, but if i get that query out of the SELECT query then it works.
Doesn't matter if it is INSERT or other query.
In console I only see: 'before insert' and no error.
This query it's in a loop.
You have syntax error in insert statement, it has to be:
connection.query('INSERT INTO users (`id`) VALUES (?)', user, function(err, result) {
console.log('insert');
if (err) throw err;
});
You could also optimise the code to run a single query only, using INSERT IGNORE syntax. If record already exists, MySQL will just ignore the insert, without giving any errors. But your field id has to be set as primary key.
Optimised, the code will look like:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '',
user : '',
password : '',
database : ''
});
[..]
connection.query('INSERT IGNORE INTO users (`id`) VALUES (?)', user, function(err, results) {
if (err) {
throw err;
} else {
callback(null, user);
}
});
I'm using MySQL for the first time, and I'm struggling to properly preparing statements and escaping query values. Here's where I'm at:
connection.connect();
formatDate(function(date){
var sql = "INSERT INTO coffee_tbl (coffee_name, coffee_type, submission_date) VALUES ?";
var inserts = [req.param('name'), req.param('type'), date];
var queryString = mysql.format(sql, inserts);
console.log(queryString)
connection.query(queryString, function(err, results){
if(err) serverError(res, err);
else{
res.redirect('/view_coffee');
}
});
});
connection.end();
I'm using the 'mysql' node.js module by felixge.
You need a ? per value. Also, be sure to use a connection pool.
formatDate(function(date){
var sql = [
"INSERT INTO coffee_tbl SET",
" coffee_name=?",
",coffee_type=?",
",submission_date=?"
].join('');
var inserts = [req.param('name'), req.param('type'), date];
pool.getConnection(function(err, connection) {
if(err) return console.error(err);
connection.query(sql, inserts, function(err, results) {
connection.release();
if(err) return console.error(err);
res.redirect('/view_coffee');
});
});
});
To setup a connection pool:
var pool = mysql.createPool({
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASS,
database: process.env.MYSQL_NAME,
connectionLimit: 8
});
Use environment variables for your mysql authentication information so as to not commit authentication information to a repo.
You only have one placeholder in your sql var, but you are trying to pass three values in your inserts var. You want to modify your sql var to have three placeholder like this:
var sql = "INSERT INTO coffee_tbl (coffee_name, coffee_type, submission_date) VALUES (?, ?, ?)";