简体   繁体   中英

Trying to pass variables into a prepared statement in JavaScript Node JS

function addEmployee() {
  inquirer
    .prompt([
      {
        name: "firstname",
        type: "input",
        message: "Enter their first name ",
      },
      {
        name: "lastname",
        type: "input",
        message: "Enter their last name ",
      },
      {
        name: "role",
        type: "list",
        message: "What is their role? ",
        choices: selectRole(),
      },
      {
        name: "choice",
        type: "rawlist",
        message: "Whats their managers name?",
        choices: selectManager(),
      },
    ])
    .then(function (val) {
      var roleId = selectRole().indexOf(val.role) + 1;
      var managerId = selectManager().indexOf(val.choice) + 1;
      db.query(
        "INSERT INTO employee (first_name, last_name, role_id, manager_id) values ('?', '?', ?, ?)?",
        {
          first_name: val.firstName,
          last_name: val.lastName,
          manager_id: managerId,
          role_id: roleId,
        },
        function (err) {
          if (err) throw err;
          console.table(val);
          startPrompt();
        }
      );
    });
}

Cannot get the INSERT into employees query statement to work. I am using the mysql2 npm package to interface with a Mysql database in Node JS. Trying to pass in the answers from the inquirer questions into the prepared statement to insert into the employees table. How do I pass in variables for the prepared statement?

Pass as array, check order of placeholders match array order and case matters on variables.

 ... db.query(` INSERT INTO employee ( first_name, last_name, role_id, manager_id ) VALUES (?, ?, ?, ?) `, [val.firstname, val.lastname, roleId, managerId]); ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM