Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs-Mysql Query table name as a variable

Tags:

node.js

mysql

How can i pass table name as variable. Basically i want to make e function in which i will take table name as a parameter and object insert record in mysql database in using nodejs My function will be like

exports.insertIntoDb = function(tableName,insertObj) {
 connection.query('INSERT INTO administrator SET ?',insertObj, function(error, result, fields) {
    if(error){
        res.json({
            status:false,
            message:'There is some problem with query'
        })
    }
    else{
        res.json({
            status : true,
            data : result,
            message: 'user registered successfully'
          })    
       }
  });
 }

But i am wondering that how to pass table name in this query which is parameter taken from function. I am asking about syntax? I am using nodejs-mysql

like image 638
Fahad Subzwari Avatar asked Sep 13 '25 07:09

Fahad Subzwari


1 Answers

Try this:

exports.insertIntoDb = function(tableName,insertObj) {
  connection.query('INSERT INTO ?? SET ?', [ tableName, insertObj ], ...)
};

Documented here: https://github.com/mysqljs/mysql#preparing-queries

like image 66
robertklep Avatar answered Sep 15 '25 22:09

robertklep