Selecting from 2 tables at one time in node js

2020-02-15 mysql node.js

I want to select all the patrols and select all the users from the database. But I got an error and I'm not sure why is it even an error.

The code that I wrote

connection.query("SELECT * FROM patrols; SELECT * FROM user", function (err, result, field){
    if (err){
         return console.log('error: ' + err.message);
    }

    res.render('patrol_schedule', {result: result, name: name});
});

The error message

 ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT * FROM user' at line 1

Answers

You can't do two queries in one call to connection.query(). Do the second query in the callback function of the first.

connection.query("SELECT * FROM patrols", function(err, patrol_result) {
  if (err) {
    return console.log('error: ' + err.message);
  }
  connection.query("SELECT * FROM user", function(err, user_result) {
    if (err) {
      return console.log('error: ' + err.message);
    }
    res.render('patrol_schedule', {
      patrol: patrol_result,
      user: user_result
    });
  });
});

Related