I keep getting an ER_PARSE_ERROR about SQL syntax when trying to insert user data into my database. I have a JavaScript object called userInfo that has three properties: name, emailAddress, and userPassword.
let insertQuery = 'insert into members (name,emailAddress,userPassword) values (' + userInfo.name + ',' + userInfo.emailAddress + ',' + userInfo.userPassword + ')' // SQL command
connection.query(insertQuery, (error, data) => {
if(error) throw error
res.send('Registration completed successfully')
})
The error message says there is something wrong with my SQL syntax but I cannot figure out what is causing this issue. Has anyone faced this problem before?
Your issue is string concatenation in the SQL statement. When you concatenate strings directly, the values aren’t properly quoted and you get syntax errors. Don’t build the query string manually - use parameterized queries instead. They’re way safer and prevent SQL injection attacks. Try this: connection.query('INSERT INTO members (name, emailAddress, userPassword) VALUES (?, ?, ?)', [userInfo.name, userInfo.emailAddress, userInfo.userPassword], callback). The question marks are placeholders and MySQL safely inserts your values. It also handles data types automatically and escapes special characters that would break your query.
you gotta add quotes around the string vals in your SQL query. change it to: 'insert into members (name,emailAddress,userPassword) values ("' + userInfo.name + '","' + userInfo.emailAddress + '","' + userInfo.userPassword + '")'. better yet, use parameterized queries, they’re way more secure.
Had this exact problem when I started with MySQL and Node.js. Your string values need quotes, but there’s a bigger issue here. Building SQL queries with string concatenation opens you up to SQL injection attacks. Learned this the hard way when someone exploited my registration form by injecting malicious SQL. What fixed it for me was switching to prepared statements with the mysql library’s parameterization. Pass your values as an array instead of concatenating strings - the library handles the escaping and quoting for you. Fixes your syntax error and protects your database from attacks.