I'm trying to parse a URL in an Express backend but when I go to a url like http://localhost:5000/reset-password?token=Wp+JCrZGAHEbDgyC4BExpWkX17Y0eurUZMu0zmu7J/5S3ChuRXoi3qdBFtdt6UlOJvMlsR4dOlMwlUS/u9UbWQ==&email=test#test.com I get error: ER_PARSE_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 '(email,token) VALUES ('test#test.com', 'Wp JCrZGAHEbDgyC4BExpWkX' at line 1
My code:
router.get('/reset-password', function(req, res, next) {
const token = req.query.token;
const email = req.query.email;
connection.query('SELECT * FROM resettoken(email,token) VALUES (?, ?)', [email, token], function(err, result) {
if (err) throw err;
Where have I gone wrong? Why req.query.token takes only part of token 'Wp JCrZGAHEbDgyC4BExpWkX' instead of 'Wp+JCrZGAHEbDgyC4BExpWkX17Y0eurUZMu0zmu7J/5S3ChuRXoi3qdBFtdt6UlOJvMlsR4dOlMwlUS/u9UbWQ=='
Problem was with connection.query, right one is:
connection.query('SELECT * FROM resettoken WHERE email = ? AND token = ?', [email, token], functi...
Related
I am facing a problem when I query data that does not follow a regex. My backend is all set and working well but when I test this controller:
exports.getInvalidPhone = (req, res, next) => {
sequelize
.query(
"SELECT * WHERE distination_phone NOT REGEXP /^(009665|9665|+9665|05|5)(5|0|3|6|4|9|1|8|7)([0-9]{7})$/ ",
{ type: QueryTypes.SELECT }
)
.then((result) => {
res.send(result);
})
.catch((err) => {
console.error(err);
});
};
I get this error
DatabaseError [SequelizeDatabaseError]: 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
'/^(009665|9665|+9665|05|5)(5|0|3|6|4|9|1|8|7)([0-9]{7})$/' at line 1
I can't insert json value into table.
const mysql = require('mysql');
const user = {};
const connection = mysql.createConnection({
host:'localhost',
user:'root',`enter code here`
password:'homi98',
database:'homi',
port:'3306',
});
user.path = "C:\\nodejsWorkspace\\Mysql";
user.date = "20190805";
user.weather = "sunny";
user.temp = 31;
user.day = "월요일";
console.log(user);
connection.connect();
connection.query('insert into homi01 (path,date,weather,temp,day) values (.$user[\'path\'].,\'20190805\',\'sunny\',31,\'월요일\'); '
,(error, results, fields) => {
if(error) throw error;
console.log(results);
});
connection.end();
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['path'].,'20190805','sunny',31,'월요일')' at
line 1
at Query.Sequence._packetToError
The query is not syntactically incorrect due to the way you are extracting values from your object. Use Template Strings to make this kind of concatenation simpler.
connection.query(`insert into homi01 (path, date, weather, temp, day) values ( "${user.path}", 20190805, "sunny", 31, "월요일"`
,(error, results, fields) => {
if(error) throw error;
console.log(results);
});
Edit:
If you have problems using Template Strings, here is how your query will be logged:
var user = {path: 'c:\\temp'}
console.log(`insert into homi01 (path, date, weather, temp, day) values ( "${user.path}", 20190805, "sunny", 31, "월요일"`);
Getting a syntax error here but can't figure out why?
Have tried using con.escape as well. Gives the same error.
var sql1 = "INSERT INTO Captcha (Captcha_Image) VALUES ('"+imgBase64+"') WHERE Session_ID = '"+x+"'";
await con.query(sql1, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
//Both imgBase64 and x are varchar values and are being stored in correctly
how to solve this 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 'WHERE Session_ID =
'93e23e3f7d17b1c50107aa6277cb303985e38e1a5faa0a505064806c291a' at line
1
Insert statements in SQL don't have a WHERE clause, so the following should work without error:
var mysql = require('mysql');
var con = mysql.createConnection({ ... });
var sql1 = "INSERT INTO Captcha (Captcha_Image) VALUES (?)";
con.query({
sql: sql1,
timeout: 40000,
},
[imgBase64],
function (error, results, fields) {
}
);
However, a WHERE clause might make sense if you were doing an INSERT INTO ... SELECT, with a select query serving as the source of data to be inserted. Something like this:
INSERT INTO Captcha (Captcha_Image)
SELECT Captcha_Image
FROM some_other_table
WHERE Session_ID = '93e23e3f7d17b1c50107aa6277cb303985e38e1a5faa0a505064806c291a';
If you instead want to change the Captcha image for records which already exist in the table, based on the session id, then you should be doing an update, not an insert:
con.query('UPDATE Captcha SET Captcha_Image = ? WHERE Session_ID = ?',
[imgBase64, x],
function (error, results, fields) {
if (error) throw error;
console.log('changed ' + results.changedRows + ' rows');
}
);
I'm trying to send data from a table to the client depending on the table the user selects.
/** GET ALL VAULES IN A PARTICULAR TABLE */
serve.get('/data/:id', (req, res)=>{
dbConn.query(
'SELECT * FROM ?',
[req.params.id],
(error, rows)=>{
if(!error){
//when there is no error
res.send(rows);
}else{
//when there is an error
res.send(error);
}
});//END dbConn
});//END SERVE
From the above, I'm expecting all the data in the table, but I keep getting the error below when I do something like "localhost:1234/data/alert"
{
"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 ''alert'' at line 1",
"sqlState": "42000",
"index": 0,
"sql": "SELECT * FROM 'alert'"
}
From this I do realize that the error is because the table name is quoted; how do I fix this error?
There are two ways -
Concatenate the query string.
/** GET ALL VAULES IN A PARTICULAR TABLE */
serve.get('/data/:id', (req, res)=>{
dbConn.query(
'SELECT * FROM '+ req.params.id,
(error, rows)=>{
if(!error){
//when there is no error
res.send(rows);
}else{
//when there is an error
res.send(error);
}
});//END dbConn
});//END SERVE
Edit- as mentioned in comments by #RiggsFolly, query concatenation could lead to an Sql Injection Attack. Keep that in mind.
If you are using mysqlmodule then use built in method
/** GET ALL VAULES IN A PARTICULAR TABLE */
serve.get('/data/:id', (req, res)=>{
dbConn.query(
'SELECT * FROM ??',
[req.params.id],
(error, rows)=>{
if(!error){
//when there is no error
res.send(rows);
}else{
//when there is an error
res.send(error);
}
});//END dbConn
});//
? is for values and ?? is for escaping query identifiers.
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.