Search code examples
javascriptmysqlsqlparameterized

How to write a parameterized SQL query in javascript?


how to write a parameterized SQL Query in javascript ?

i am trying this but getting an error

i am also tried this 2 still getting syntax error

let sql =select * from q_users where firstname=?,[${name}];

let sql =select * from q_users where firstname=?,${name};

let sql =`select * from q_users where firstname=?,${[name]}`;
db.query(sql)
.then((data)=>{
    console.log(data);
});

Solution

  • The easiest would be to just stick to the extensive documentation - and learning basic javascript. The statement

    let sql =`select * from q_users where firstname=?,${[name]}`;
    

    makes no sense, it's just a string with an array at its end. It might be helpful to read up about template strings to get to know them and how to use them properly.

    The docs explain to pass two arguments to db.query(). So you will need something like

    let sql = 'select * from q_users where firstname=?';
    db.query(sql, [name]).then(...);
    

    Also, avoid using name as a variable's name.