Node.js中MySQL查询出现Unexpected identifier错误求助
Hey there! Let's break down what's going wrong here and fix it properly.
First, the immediate syntax error you're seeing: even though the SQL runs fine in phpMyAdmin, building the query with string concatenation in your Node.js code is risky and can break the JavaScript string structure. If the username variable ever contains special characters (like quotes, backslashes, or even unexpected formatting), it can split your SQL string open—making the JS engine parse part of the SQL as raw JavaScript code, hence the Unexpected identifier pointing at SELECT.
But the far bigger, critical issue here is SQL injection. Using string concatenation to build SQL queries is a massive security hole. Attackers could craft a malicious username that executes arbitrary SQL commands on your database, leading to data theft, corruption, or full system compromise.
The Fix: Use Parameterized Queries
Instead of string concatenation, leverage your database driver's built-in parameterized query support. This lets the driver handle escaping special characters automatically, eliminating both syntax errors and SQL injection risks entirely.
Here's how to rewrite your code correctly:
connection.query( "SELECT * FROM accounts_data WHERE new_username LIKE ?", [`%${username}%`], // Pass parameters as an array function (error, results, fields) { if (error) { console.error(error); return; } // Process your query results here } );
Why This Works
- The
?in the SQL acts as a safe placeholder for your parameter. - The driver takes the
%${username}%value, properly escapes any dangerous characters, and inserts it safely into the query. - No more broken strings, no more SQL injection vulnerabilities.
To circle back to your original syntax error: even if your current username value (preloved_bys) looks harmless, it's likely that at some point (maybe a test case you ran earlier), username contained a character that broke the string—like a single quote or double quote. Parameterized queries eliminate this problem for good.
内容的提问来源于stack exchange,提问作者adit

