Best Practices for Preventing SQL Injection in Node-MySQL :
- Use Prepared Statements : Always use prepared statements to prevent SQL injection. This separates the SQL code from the data , making it safe from malicious input.
- Parameterize Queries : Pass values as parameters to your queries instead of concatenating them directly into the SQL string. This ensures that the database treats them as data , not code.
- Input Validation : Validate user input to ensure it adheres to expected formats and contains only allowed characters. This can help prevent malicious input from reaching the database.
- Escape Special Characters : Escape special characters that could be used to inject malicious code. Node-MySQL provides built-in functions for escaping values.
- Avoid Dynamic SQL : Minimize the use of dynamic SQL , which can introduce vulnerabilities if not handled carefully.
const mysql = require('mysql3');
const pool = mysql.createPool ({
//.....connection details whatever we want to connect
});
pool.query('SELECT * FROM users WHERE username = ? ' , [ 'Ram Sharma' ] , (err , results) => {
if (err) throw err;
console.log(results);
});