How to parse email in node js mysql? - mysql

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.

Related

Node.js and mysql. Insert into local database

I am currently working on a html form that allows the user to input their title, firstname, surname, mobile and email. Currently this data is being pushed into an in-memory database called userDatabase[].
I want to be able to insert the data into my local mysql database instead. I can connect to my database using this code with no issues.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "user",
password: "password",
database: "user",
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
In the below code you can see that the data is getting pushed into the in-memory database.
if (currentMethod === "POST") {
// read the body of the POST request
request.on("data", function(chunk) {
requestBody += chunk.toString();
});
// determine the POST request Content-type (and log to console)
// Either: (i) application/x-www-form-urlencoded or (ii) application/json
const { headers } = request;
let ctype = headers["content-type"];
console.log("RECEIVED Content-Type: " + ctype + "\n");
// finished reading the body of the request
request.on("end", function() {
var userData = "";
// saving the user from the body to the database
if (ctype.match(new RegExp('^application/x-www-form-urlencoded'))) {
userData = querystring.parse(requestBody);
} else {
userData = JSON.parse(requestBody);
}
//**************** */
userDatabase.push(userData)
I have tried to INSERT the data into my table called "personal" like this: But I am getting an error Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'title = 'ms', firstname = 'Tina', surname = 'poole', mobile = '+3...' at line 1
con.query("INSERT INTO personal (title , firstname, surname, mobile , email ) VALUES ?", [userData], function(err, result) {
if (err) throw err;
console.log("1 record inserted");
});
You're conflating two distinct syntax patterns for MySQL's INSERT. In these types of situations you should be referring to the relevant documentation.
When specifying key='value' pairs, the syntax for an INSERT would conform to the following format:
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name [, partition_name] ...)]
SET assignment_list
[ON DUPLICATE KEY UPDATE assignment_list]
This format is clearly delineated from the traditional INSERT INTO tbl_name (fieldnames) VALUES (values) as it doesn't require either the field names nor the VALUES keyword, as you've included in your query syntax above. Instead, you'd include the SET <assignment_list> sequence, which operates similarly in syntax to a traditional UPDATE query.
Instead, your code would look similar to the following:
con.query("INSERT INTO personal SET ?", [userData], function(err, result) {
if (err) throw err;
console.log("1 record inserted");
});

Inserting multiple arrays from post method

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);

Looping through JSON file and inserting into mysql database table using node.js

I have a number of values in a JSON file set out as follows:
[{"scraped_at": 1533384162.2934802, "server_id": "461235834994032661", "invite_code": "5uWt6B", "server_name": "Magic Pokemon", "members": ["115385224119975941", "133557837598031872"]}
As can be seen the last value is another array. I've been trying to use the following code to insert into the mysql database using node.js:
const fs = require('fs');
var obj;
const mysql = require('mysql');
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "list"
});
fs.readFile('list.json', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
for(var i = 0; i < obj.length; i++) {
const s_at = obj[i].scraped_at;
const s_id = obj[i].server_id;
const s_inv = obj[i].invite_code;
const s_sn = obj[i].server_name;
const mbs = obj[i].members;
const sql = 'INSERT INTO members (scraped_at, server_id, invite_code, server_name, servermbs) VALUES ('+s_at+','+s_id+','+s_inv+','+s_sn+','+mbs+')';
con.query(sql, function (err, result) {
if (err) throw err;
console.log("x record inserted");
});
}
});
});
I'm currently getting the following error thrown:
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 'RP,115385224119975941,133557837598031872,160105994217586689,212681528730189824,2' at line 1
Anyone got any ideas what is up with it and if so any solutions?
Apologies if the code doesn't look too great as I've never been good at formatting on this community site.
Thanks!

Nodejs inserting into database fails

I've been trying to make this script work with value binds, but seems it doesn't work with the mainTable variable.
var mainTable = "tasks";
var con = mysql.createConnection({
host: "host",
user: "user",
password: "password",
database: "database"
});
con.connect(function (err) {
if (err) throw err;
console.log("Connected!");
var values = {
id: "id",
url: "url",
assignee: "akjdh",
status: "ahsbdu",
type: "apsokdn",
description: "asd",
department: "department"
};
var query = con.query("INSERT INTO ? SET ? ON DUPLICATE KEY UPDATE ?", [
mainTable,
values,
values
], function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
I get the following error:
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 ''tasks' SET id = 'id', url = 'url', assignee = 'akjdh', status = 'ahsbdu' at line 1
I don't understand why its failing with if I make the table value into a bind.
Mysql identifiers have to be escaped using a backtick ` and not using '.
? is used to escape value with '
?? is used to escape identifiers with `
As of that it hast to be:
INSERT INTO ?? SET ? ON DUPLICATE KEY UPDATE ?
mysql: Escaping query identifiers
Alternatively, you can use ?? characters as placeholders for identifiers you would like to have escaped like this:

Received invalid field length error in nodejs with mysql application

I'm getting below error while fetching records (apx 50 rows) from my sql database. My application is developed in nodejs with express.
var common = require(__base + 'routes/common.js');
var dbhelper = require(__base + 'routes/dbhelper.js');
exports.GetStates = function (callback) {
dbhelper.pool.getConnection(function (err, connection) {
// Use the connection
connection.query('CALL GetStates()',
function (err, res) {
connection.release();
if (err) {
common.ActionOutput.Status = common.ActionStatus.Error;
common.ActionOutput.Message = 'System Error: ' + err.message;
} else {
common.ActionOutput.Status = common.ActionStatus.Success;
common.ActionOutput.Result = res[0][0];
}
return callback(JSON.stringify(common.ActionOutput));
});
});
};
dbhelper.js is
// Database connection
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 10,
host: 'my ip',
user: 'user',
password: 'pass',,
database: 'ssdsdas'
});
exports.pool = pool;
I ran into the same error message but the causes of our issues might be different. Ultimately, the cause of my issue is that the column names in my stored procedure did not have back ticks (`) resulting in them being treated as variables.
Adding back ticks in my stored procedure body for column names fixed it.