Trying to add a row to a mysql table using node.js, but keep getting a syntax error. New to both node/express and MySQL (downloaded the most recent versions of both a few days ago). Have compared my code with other examples and cannot figure out what is driving the error for the life of me. Code and console output below.
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const passport = require('passport');
const mysql = require('mysql');
const con = mysql.createConnection({
host: 'localhost',
user: 'theuser',
password: 'thepassword',
database: 'thedatabase'
});
con.connect(function(err) {
if (err) throw err;
console.log('User Connected!');
});
const date1 = new Date();
const newUser = {
first_name: first_name1,
last_name: last_name1,
email: email1,
password: password1,
date: date1
};
const newUser_val = Object.values(newUser)
console.log(newUser_val)
const sql = "INSERT INTO webusers (first_name, last_name, email, password, register_date) VALUES ?";
con.query(sql, [newUser_val], function (err, result, fields) {
if(result) {
req.flash('success_msg', 'You are now registered');
res.redirect('../')
} else {
console.log(err);
};
});
And here is the relevant console output
User Connected!
[
'Pete',
'Sample',
'pete#gmail.com',
'$2a$10$6ufJWiCaubg8WjE.0AHqrOFi0z3W97mSN48v.vdO7pcl20ZPRBhXW',
2020-03-31T18:54:16.474Z
]
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: "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 ''Pete', 'Sample', 'pete#gmail.com', '$2a$10$6ufJWiCaubg8WjE.0AHqrOFi0z3W97mSN48v' at line 1", sqlState: '42000',
index: 0,
sql: "INSERT INTO webusers (first_name, last_name, email, password, register_date) VALUES 'Pete', 'Sample', 'pete#gmail.com', '$2a$10$6ufJWiCaubg8WjE.0AHqrOFi0z3W97mSN48v.vdO7pcl20ZPRBhXW', '2020-03-31 14:54:16.474'"
}
Not sure why my question was down voted without any comment, but alas I figured it out. "?" needs parentheses as corrected in code below:
var sql = "INSERT INTO webusers (first_name, last_name, email, password, register_date) VALUES ( ? );";
These parentheses are missing from a lot of the examples out there and were necessary to make my code work... hope it helps.
Related
I am new to node.js and learning it for quite few days and now I'm stuck with this app.post which is not working for me. If possible please let me know how to do app.update so it might be a big help in my learning process.
Kindly waiting for reply.
const mysql = require('mysql');
const express = require('express');
var app = express();
const bodyparser = require('body-parser');
app.use(bodyparser.urlencoded({extended: false}));
app.use(bodyparser.json());
app.listen(8000);
var mysqlconnection = mysql.createConnection(
{
host: 'localhost',
user: 'Naveen',
password: '',
database: 'employeedb',
multipleStatements: true
}
);
mysqlconnection.connect((err)=>{
if(!err)
console.log("DB connection successfull");
else
console.log('DB connection failed \n Error : '+ JSON.stringify(err, undefined, 2) );
});
app.post('/employee' ,function (req, res, next) {
Name = req.query.Name,
Empcode = req.query.Empcode,
Salary = req.query.Salary
let sql = "INSERT INTO employee (Name, Empcode, Salary) VALUES (? , ?, ?)";
mysqlconnection.query('sql, (Name, Empcode, Salary) ', (err, rows, fields) => {
if (!err)
res.send("Insert succeed");
else
console.log(err);
});
});
```
and then I get these error messages:
**PS C:\xampp\htdocs\first app> node index.js DB connection successfull 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 'sql, (Name, Empcode, Salary)' at line 1
(C:\xampp\htdocs\first app\node_modules\express\lib\router\index.js:275:10) { code: 'ER_PARSE_ERROR', errno: 1064, sqlMessage: "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 'sql, (Name, Empcode, Salary)' at line 1", sqlState: '42000', index: 0, sql: 'sql, (Name, Empcode, Salary) ' }**
You have typo in your query.
// WRONG
mysqlconnection.query('sql, (Name, Empcode, Salary) ', (err, rows, fields)...
It should not be inside quotes, and variables should be an array.
// CORRECT
mysqlconnection.query(sql, [Name, Empcode, Salary], (err, rows, fields)...
The error is clear. It is saying "You have an error in your SQL syntax". And you should check your syntax at "near 'sql, (Name, Empcode, Salary)'".
This line here
mysqlconnection.query('sql, (Name, Empcode, Salary) ',
you are passing the string literal "sql, (Name, Empcode, Salary) ", while you meant to pass in the variable sql that you created in the line above.
I'm writing code for Discord, this is my code:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mydb"
});
var name = 'name';
var id = '1';
var sql = 'SELECT * FROM customers WHERE name = ? OR id = ?';
con.query(sql, [name, id], function(err, result) {
if (err) throw err;
console.log(result);
});
The code works and it shows me what I have in the table, now I want to design it nicely, and I have the following design:
client.on('message', message => {
if (message.content.startsWith(prefix + [name])) {
const logo = ''
const embed = new MessageEmbed()
.setTitle("name is: " + [name])
}
message.channel.send(embed);
});
Now it's working.
But my problem is that I want it to be offered to me from SQL.
This means that instead of the name I have listed every name I want I want to get results from SQL in case there is no result that will show me an error message.
Can anyone help me on this?
I am new in node.js
I am trying to make a login and registration system using express.js, vanilla JS, CSS, HTML, and MySql.
below is code that handles routing as well as parses HTTP Post requests made by the client which consists of username and password. username and password are stored inside fields.username and fields.password
functions userRegistration(...) and userLogin(...) are defined inside db.js ( shown at the end ); they are exported from db.js and are imported in users.js
users.js
router.post('/register', (req, res, next) => {
const form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
var userInfoArray = [fields.username, fields.password]
db.userRegistration(userInfoArray)
})
});
router.post('/login', (req, res, next) => {
const form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
var userInfoArray = [fields.username, fields.password]
db.userLogin(userInfoArray)
})
});
I have created userinfo table to store usernames and passwords.
As shown below I am getting username and password by HTTP post method. Which I am parsing using
formidable module which gives me fields.username and fields.password values.
I am using query(...) method to query database providing actual SQL as string named registrationQueryString (to insert an entry into table) and loginQueryString(to find whether provided username and password are in the database or not)
db.js
var username, password;
var userInfoArray = [username, password]
const registrationQueryString = "INSERT INTO (username, password) userinfo VALUES ( ?, ? )"
const loginQueryString = "SELECT (username, password) FROM userinfo WHERE EXISTS (SELECT (username, password) FROM userinfo WHERE username = (?) AND password = (?))"
function userRegistration (userInfoArray){
dbConnection.query( registrationQueryString, userInfoArray, function(err, results, fields) {
if (err) throw err
console.log(results)
})
}
function userLogin (userInfoArray){
dbConnection.query( loginQueryString, userInfoArray, function(err, results, fields) {
if (err) throw err
console.log(results)
})
}
It is giving me an error
"wer" is random value I provided as username and password
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 '(username, password) userinfo VALUES ( 'wer', 'wer' )' at line 1
at Query.Sequence._packetToError (F:\dr.server\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Query.ErrorPacket (F:\dr.server\node_modules\mysql\lib\protocol\sequences\Query.js:79:18)
at Protocol._parsePacket (F:\dr.server\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (F:\dr.server\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (F:\dr.server\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (F:\dr.server\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (F:\dr.server\node_modules\mysql\lib\Connection.js:88:28)
at Socket.<anonymous> (F:\dr.server\node_modules\mysql\lib\Connection.js:526:10)
at Socket.emit (events.js:400:28)
at addChunk (internal/streams/readable.js:290:12)
--------------------
at Protocol._enqueue (F:\dr.server\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Connection.query (F:\dr.server\node_modules\mysql\lib\Connection.js:198:25)
at Object.userRegistration (F:\dr.server\db.js:29:18)
at F:\dr.server\routes\users.js:12:8
at zalgoSafe (F:\dr.server\node_modules\dezalgo\dezalgo.js:20:10)
at f (F:\dr.server\node_modules\once\once.js:25:25)
at IncomingForm.<anonymous> (F:\dr.server\node_modules\formidable\src\Formidable.js:183:9)
at IncomingForm.emit (events.js:400:28)
at IncomingForm._maybeEnd (F:\dr.server\node_modules\formidable\src\Formidable.js:612:10)
at QuerystringParser.<anonymous> (F:\dr.server\node_modules\formidable\src\plugins\querystring.js:36:10) {
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: "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 '(username, password) userinfo VALUES ( 'wer', 'wer' )' at line 1",
sqlState: '42000',
index: 0,
sql: "INSERT INTO (username, password) userinfo VALUES ( 'wer', 'wer' )"
}
I know that something is wrong with my SQL queries but I am not able to figure it out.
Any help will be welcomed.
If this information isn't enough I can give specific code through github.
Not able to add a comment, yet. Have you tried to change your SQL statement to:
INSERT INTO tbl_name (col_name, col_name) VALUES ('value', 'value')
"INSERT INTO userinfo (username, password) VALUES ( 'wer', 'wer' )"
https://dev.mysql.com/doc/refman/8.0/en/insert.html
Edit:
In your post:
It is giving me an error
I know that something is wrong with my SQL queries but I am not able to figure it out.
The code above is not meant to be the answer. As I previously mentioned, not able to comment, yet. The above code is just a pointer to the correct answer. You have to change your MySQL query to the syntax above. The link provided gives you the correct syntax.
"insert into userinfo(username, password) values('wer', 'wer');"
You can use template literals to do so.
var username, password;
const registrationQueryString = `INSERT INTO (username, password) userinfo VALUES ('${username}', '${password}')`
And then use registrationQueryString as a raw query.
Bear in mind this is an ES2015 feature and should be available in any recent version of Node.js. More about template literals at MDN Web Docs
First update this query from
INSERT INTO (username, password) userinfo VALUES ( ?, ? )
to
INSERT INTO userinfo (username, password) VALUES ( ?, ? )
Please don't use this type of query
SELECT (username, password) FROM userinfo WHERE EXISTS (SELECT (username, password) FROM userinfo WHERE username = (?) AND password = (?))
Replace it with the following
const ObjQr = [
req.body.username,
req.body.password
];
const SsQl = "CALL SpSelectUser(?,?)";
query(SsQl, ObjQr, (err,results,fields) => {
if(err) {
res.send('ERROR');
}
else {
const Info= {
UserInfo : results[0]
};
res.json(Info);
}
});
Try to use StoredProcedure instead of direct query to avoid race condition and Sql-Injection.
My code:
const Discord = require("discord.js");
var mysql = require('mysql');
exports.run = (client, message) => {
var con = mysql.createConnection({
host: "******",
user: "******",
password: "******",
database: "*******"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT ActivationKey FROM whitelists WHERE DiscordID = '" + message.author.id + "'", function (err, rows, fields) {
if (err) throw err;
console.log(rows);
message.channel.send(rows);
});
};
);
};
The Discord Chat Output https://imgur.com/vzUXNbA
The Console Output https://imgur.com/8zUxvIJ
The MySQL Setup https://imgur.com/GJoUuY7
Any help would be greatly appriciated. Please point out even the most obvious, I'm sort of new to Javascript.
I know I'm probably being an idiot, but this issue is really frustrating me and hindering my progress.
Thanks,
Timothy
You have to extract what you need to from rows that seems an array of objects:
rows rapresentation:
[
{
ActivationKey : "WWWW-XXXX-YYYY-ZZZZ"
}
]
You can try with this code:
message.channel.send(rows[0].ActivationKey);
You should be able to use the util package to log the object in depth
const util = require('util')
console.log(util.inspect(myObject))
New to node.js and just cant figure out how to do the following:
I have this on my db module:
var mysql = require('mysql');
var MY_DATABASE='nodejs_mysql';
var client = mysql.createClient({
user: 'root',
password: 'root',
});
and im building this table:
client.query(
'CREATE TEMPORARY TABLE '+USER+
'(username VARCHAR(255), '+
'password VARCHAR(255), '+
'name VARCHAR(255), '+
'picture VARCHAR(255), '+
'PRIMARY KEY(username))'
);
and later on, i want to perform this:
client.query('select username, password from ' + USER + 'where username=?',[req.body.username] , 'AND password=?', [req.body.password]
function (err, results, fields) {
if (err) {
throw err;
}
//some actions performed here
});
all of those are in the same dataBase.js file.
how can i send username and password from another file named: server.js
as parameters to the query written above and get a certain value back?
is there any way to do that?
Ok, I think I get it now. You create temporary table in dataBase.js and want to perform query in this table in request handler in server.js. If that's it, you should consider following aproach:
// dataBase.js
var mysql = require('mysql');
var MY_DATABASE='nodejs_mysql';
// connect to database
var client = mysql.createClient({
user: 'root',
password: 'root',
});
// create temporary table
client.query(
'CREATE TEMPORARY TABLE '+USER+
'(username VARCHAR(255), '+
'password VARCHAR(255), '+
'name VARCHAR(255), '+
'picture VARCHAR(255), '+
'PRIMARY KEY(username))'
);
// that's what I think you need. And yes, it looks like "a good to rap" for me.
module.exports.getInfoFromTemporaryTable : function( username, password, callback) {
client.query(
'select username, password from ' + USER + 'where username=?',
[req.body.username] , 'AND password=?', [req.body.password],
callback
);
}
The only thing I can't figure out is where you get USER variable from. Pay attention to this moment. Maybe pass it to getInfoFromTemporaryTable() function.
// server.js
var db = require('./lib/dataBase');
app.get(someRoute, function(req, res) {
db.getInfoFromTemporaryTable( req.body.username, req.body.password,
function(err, results, fields) {
if (err) {
// handle errors or something
return;
}
// do what you need to do, using results you got from temp table
});
});
I'm not familiar with MySQL module you using, so above code is more like a general idea of what you need to implement. Hope it will help.
how can i send username and password from another file named: server.js
as parameters to the query written above and get a certain value back?
Use the exports object. See here for more information on NodeJS's module system.
// server.js
exports.username = function {
return "foo";
};
exports.password = function {
return "bar";
};
// database.js
require('./server.js');
var client = mysql.createClient({
user: server.username, // exports.username in server.js
password: server.password, // exports.password in server.js
});
Why are you splitting your query up?
// server.js
exports.username = "Your username.";
exports.password = "Your password.";
// dataBase.js
// ... mysql connection setup ...
var server = require("./server");
client.query('SELECT username, password FROM `' + USER + '` WHERE username=? AND password=?',
[server.username, server.password],
function (err, results, fields) {
if (err) {
throw err;
}
// ... some actions performed here ...
}
);
I'm not exactly sure what you were asking, but I think this should at least get you closer to your answer.