I am trying to post a row into a mysql database using data from an express form but always get SQL syntax errors
router.post('/add', function(req, res, next) {
var title = req.body['title'];
var director = req.body['director'];
var release = req.body['release'];
var review = req.body['review'];
connection.query("INSERT INTO films.filmStore (title, director, review, release) VALUES ('" + title.toString() + "', '" + director.toString() + "', '" + review.toString() + "', '" + release.toString() + "');", function(err, result){
if(err) throw err;
console.log("1 record inserted");
});
res.redirect('/');
});
However I get an error
throw err; // Rethrow non-MySQL errors
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 'release) VALUES ('Superman', 'Richard Donner', 'One of the best films of all tim' at line 1
I've tried everything I can think of but I'm new to SQL and can't figure out what's different from other examples I've seen.
release is a reserved keyword in mysql.
See: https://dev.mysql.com/doc/refman/8.0/en/keywords.html
Either alter the name of that column or use backticks:
"INSERT INTO films.filmStore (title, director, review, `release`) VALUES (..."
Related
I'm trying to feed an Array of data formatted like this
[ 3717003570,'HYDRAULIC ACTUATOR','DIAMEC','EXPLORATION',2,16071.59]
and its returning the error saying
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 '3717003570, 'HYDRAULIC ACTUATOR', 'DIAMEC',
'EXPLORATION', 2, 16071.59' at line 1
While when I try to manually insert the data with a query in SequelPro it isn't throwing any sort of error
EDIT: Whole statement
var query = "INSERT INTO products (ITEMNO, DESCRIPTION, MODEL, CATEGORY, QTY, PRICE) VALUES ?";
con.query(query, values, (err, results)=> {
if (err) throw err;
console.log("Sucess, Rows Affected:" + results.affectedRows);
})
Below is my code for mass insert into my MYSQL Db
connectionPool.getConnection(function(err, connection){
if(err) {
winston.log('info', '------- ERROR while getting connection: ' + err.message);
connection.release();
return;
}
connection.query('INSERT INTO PollOptions (idPollOption, Option, PollId) values ?', [pollOptionsArray], function(err, rows){
if(err) {
winston.info('info', '----------------------- ERROR: ' + err);
connection.release();
return;
}
connection.release();
});
});
Where the pollOptionsArray is
[
["POPE1lrKXMy9Q","Adam","POLL4yrFXzkcX"],
["POPVy-StXGJcm","Mike","POLL4yrFXzkcX"],["POPNkMSFmGy97","Lucy","POLL4yrFXzkcX"]
]
The database table has the following columns
idPollOption, Option, PollId (all VARCHAR)
It gives me the following error:
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 'Option, PollId) values ('POPE1lrKXMy9Q',
'Adam', 'POLL4yrFXzkcX'), ('POPVy-StXGJ' at line 1
I even tried to hardcode my sql input like this:
var temp = [
['123', 'demian#gmail.com', 'POLLVJsBGIjYQ'],
['345', 'john#gmail.com', 'POLLVJsBGIjYQ'],
['567', 'mark#gmail.com', 'POLLVJsBGIjYQ'],
['678', 'pete#gmail.com', 'POLLVJsBGIjYQ']
];
But it still gives me the same error. I don't understand what I am doing wrong. Clearly my SQL syntax is incorrect at the values but what is the remedy?
I even tried to remove the '[]' in the pollOptionsArray and it gives me the same error.
Any idea what is going on here?
So there was no issue with my syntax. The problem was the column named "Option".
Apparently "Option" is a reserved keyword in MySQL and since I used it to name my column, it was giving me trouble.
I'm having a little trouble performing an update query with the node mysql2 module. I'm preparing the query using the '?' placeholder and then passing in the values like so;
socket.on('connection', function(client){
[...]
client.on('userjoin', function(username, userid){
run_db_insert("UPDATE users_table SET clientid = ? WHERE user = ?", [client.id, userid], function(){
console.log(client.id + ' <=> ' + userid);
});
[...]
});
Unfortunately, this is raising an 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 ''12345678' WHERE userid = ?' at line 1
The data isn't reflected in the database. For some reason, the code doesn't appear to be picking up the second question mark placeholder and so it's not passing the correct value (i.e. it's trying to find the userid of ?).
If I change the code to this;
run_db_insert("UPDATE users_table SET clientid = ? WHERE user = '" + userid + "'", [client.id], function(){
...then the update runs without error and is reflected in the DB. If I console.log both client.id and userid, the console correctly reflects these values.
My run_db_insert function is as follows;
function run_db_insert(sql, args, callback){
var mysql = svc_mysql2.createConnection({
// connection details
});
mysql.connect(function(err){
if(err){
console.log('Error connecting to DB: ' + err);
}
});
mysql.query(sql, [args], function(err){
if (err){
console.log(err);
return;
}
callback();
});
mysql.end();
};
I've had no problems performing SELECT or INSERT queries using multiple '?' placeholders (with a slightly modified function that has result in the line 11 of that function and then returns that in the callback), but I'm finding that UPDATE isn't correctly assigning all the parameters I'm passing in to it.
I think your problem is that you're wrapping your query replacement values in another array, so [[client.id, userid]] is being passed to mysql.query().
Try changing:
mysql.query(sql, [args], function(err){
to:
mysql.query(sql, args, function(err){
i trying to insert json created in node.js into mysql,
but there is a error in syntax, i am not able to rectify the error,
any help will be appreciated
my code
flowController.on('2', function (_selfid,_participantId,_groupid,_allMemberContent)
{
var allMemberDetailSQL= "SELECT spFunAllMemberNotificationDetails("+ _selfid + "," + _participantId +") as groupparticipants";
console.log("allMemberDetailSQL"+allMemberDetailSQL);
client.query(allMemberDetailSQL,function(detailERROR,detailResult)
{
if (detailERROR)
console.log("detailERROR "+ detailERROR);
else
{
var detailstr='';
detailstr = JSON.stringify(detailResult);
console.log('detailResult :'+ detailstr);
console.log("detailResult "+detailResult[0].groupparticipants);
var otherArray = [detailResult[0].groupparticipants];
var _allMemberDetail = JSON.stringify({
selfid: _selfid,
groupid: _groupid,
anArray: otherArray
});
console.log("_allMemberDetail " +_allMemberDetail);
var allMemberDetail = "'"+_allMemberDetail+"'";
console.log("allMemberDetail "+allMemberDetail);
client.query("INSERT INTO cmNotification (notificationSenderId, notificationReceiverId)"+"VALUES('"+_selfid+"','"+ _allMemberDetail+ "');", function(err, rows)
{
console.log("error insert "+err);
console.log("rows insert"+rows);
//connection.release();
});
}
});
});
console output
allMemberDetailSQLSELECT spFunAllMemberNotificationDetails(20,16) as groupparticipants
detailResult :[{"groupparticipants":"userid:'15',firstname:'pitu15',lastname:'',isfriend:'1',profilepicurl:''"}]
detailResult userid:'15',firstname:'pitu15',lastname:'',isfriend:'1',profilepicurl:''
_allMemberDetail {"selfid":"20","groupid":"15","anArray":["userid:'15',firstname:'pitu15',lastname:'',isfriend:'1',profilepicurl:''"]}
allMemberDetail '{"selfid":"20","groupid":"15","anArray":["userid:'15',firstname:'pitu15',lastname:'',isfriend:'1',profilepicurl:''"]}'
detailResult :[{"groupparticipants":"userid:'16',firstname:'pitu16',lastname:'',isfriend:'0',profilepicurl:''"}]
detailResult userid:'16',firstname:'pitu16',lastname:'',isfriend:'0',profilepicurl:''
_allMemberDetail {"selfid":"20","groupid":"15","anArray":["userid:'16',firstname:'pitu16',lastname:'',isfriend:'0',profilepicurl:''"]}
allMemberDetail '{"selfid":"20","groupid":"15","anArray":["userid:'16',firstname:'pitu16',lastname:'',isfriend:'0',profilepicurl:''"]}'
error insert 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 '15',firstname:'pitu15',lastname:'',isfriend:'1',profilepicurl:''"]}')' at line 1
rows insertundefined
error insert 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 '16',firstname:'pitu16',lastname:'',isfriend:'0',profilepicurl:''"]}')' at line 1
rows insertundefined
Use built in parameters escaping to prevent sql injection attack. "INSERT INTO ... SET ?" also makes life easier:
client.query("INSERT INTO cmNotification SET ?", {notificationSenderId: _selfid, notificationReceiverId: _allMemberDetail}, function(err, rows) {
// ...
});
This seems like it should be super easy, and I have been stuck for about two hours now. Four separate people have looked at and not found an obvious problem. So again I turn to the SO community.
Real simple - I am just trying to insert data in a mysql database via mysql-node. I am getting no connection errors, and SELECT works just fine. The code being used is:
exports.postNewCast = function(data, res) {
var query = "INSERT INTO cast (name, portrait, role, bio) VALUES ('" + data.name + "', '" + data.portrait + "', '" + data.role + "', '" + data.bio + "');";
console.log(query);
dbConnection.query(query, data, function(err, result) {
if (err) {
console.log(err);
} else {
sendResponse(res, "Cast Member Added", 201);
}
});
};
The error being logged is:
{ [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 'cast (name, portrait, role, bio) VALUES ('Jessie', 'images/cast/marissa.jpg', 'L' at line 1]
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlState: '42000',
index: 0 }
The weird part (for me) is that I can copy from my terminal window (where the server is running) the console.logged query string, and paste it into the mysql command line, and it works just fine. I have tried using GRANT to make sure the user server is running has permissions, and this did nothing. I have tried copying / pasting INSERT INTO syntax straight from working sources, and only replacing my data-specific fields. I have tried using the VALUES ? option, followed by a data object, and got the same result.
So what stupid mistake am I making?
Thanks.
Ilya Bursov had it correct, adding this answer for posterity. I am not sure if 'cast' is a reserved word or what, but I needed back ticks (" ` ") around the table name to get it working.
Try to put `` around each column name like this
"INSERT INTO cast (`name`, `portrait`, `role`, `bio`) VALUES ('" + data.name + "', '" + data.portrait + "', '" + data.role + "', '" + data.bio + "');";