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.
Related
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...
I am trying to insert some data on my app. On my db.js:
usersDB.create = async (name, age, contact) => {
return new Promise((resolve, reject) => {
pool.query(
"INSERT INTO users(name=?, age=?, contact=?) VALUES(?,?,?)",
[name, age, contact],
(err, results) => {
if (err) {
return reject(err);
}
return resolve(results);
}
);
});
};
Then on my router.js:
router.post("/", async (req, res) => {
try {
let results = await db.create(
req.body.name,
req.body.age,
req.body.contact
);
res.send({ message: "Created users" });
} catch (error) {
console.log(error);
res.sendStatus(500);
}
});
This however, returns an INTERNAL SERVER ERROR on postman and returns the ff on my console:
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 '='Your Builder', age=25, contact=689566) VALUES(?,?,?)' at line 1"
Any idea what am I missing here? How do I fix it?
This line:
"INSERT INTO users(name=?, age=?, contact=?) VALUES(?,?,?)"
Contains a SQL Syntax error. Change it like this:
"INSERT INTO users (name, age, contact) VALUES (?,?,?)"
You first list the fields, without assigning anything to the single field, then you list the values you want to insert.
I want to select all the patrols and select all the users from the database. But I got an error and I'm not sure why is it even an error.
The code that I wrote
connection.query("SELECT * FROM patrols; SELECT * FROM user", function (err, result, field){
if (err){
return console.log('error: ' + err.message);
}
res.render('patrol_schedule', {result: result, name: name});
});
The error message
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 'SELECT * FROM user' at line 1
You can't do two queries in one call to connection.query(). Do the second query in the callback function of the first.
connection.query("SELECT * FROM patrols", function(err, patrol_result) {
if (err) {
return console.log('error: ' + err.message);
}
connection.query("SELECT * FROM user", function(err, user_result) {
if (err) {
return console.log('error: ' + err.message);
}
res.render('patrol_schedule', {
patrol: patrol_result,
user: user_result
});
});
});
var sql = "SELECT users.name AS user, products.name AS favorite FROM users JOIN products ON users.favorite_product = products.id";
Ref: https://www.w3schools.com/nodejs/nodejs_mysql_join.asp
I am trying to get my nodejs to insert into my mysql database, but I'm getting a parse error. Please help if anyone can see an error:
var con = mysql.createConnection({
host: "XXX",
user: "XXX",
password: "XXX",
database: "XXX"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql;
if(req.body.role == "tutor")
{
sql = 'INSERT INTO Tutor (sesh_save) VALUES ? ';
}
else if(req.body.role == "student")
{
sql = 'INSERT INTO Students (sesh_save) VALUES ?';
}
var yoy = 'yoy';
con.query(sql, yoy, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
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 ''yoy'' at line 1
Thanks again...Sorry if this is a dumb question, but mysql insertion is always the hardest thing for me to debug.
Second argument in con.query need to be an array in your case:
Add array brackets [ ] around yoy variable
con.query(sql, [yoy], function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
Alternatively add brackets ( ) in values if you don't want to use array brackets,
Replace your sql lines with following-
if (req.body.role == "tutor") {
sql = 'INSERT INTO Tutor (sesh_save) VALUES (?) ';
}
else if (req.body.role == "student") {
sql = 'INSERT INTO Students (sesh_save) VALUES (?) ';
}
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');
}
);