Nodejs-Mysql Query table name as a variable

Viewed 5474

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

2 Answers

Inside app.js:

app.put('/updateCell', async function(req, res) {
    console.log("REST: PUT /updateCell");
    let orderInfo = req.body;
    let cellValue = orderInfo.cell;
    let CustomerName = orderInfo.CustomerName;
    let ColumnName = orderInfo.columnName;

    connection.query("UPDATE vehicles SET ?? = ? WHERE order_CustomerName = ?", [columnName, cellValue, customerName],
        function(err, result) {
          if (err) throw err;
        });
        res.send();
});

example:

//cellValue = "Fluffiest hat of them all";
//customerName = "Jenny Hopkins";
//columnName = "description";

So the SQL query would be the same as:

UPDATE order SET description = "fluffiest hat of them all" WHERE order_CustomerName = "Jenny Hopkins";
Related