0

I am trying to login my user and i need to search whether the user exists in the db or not. My db is ClearDB using MySQL on Heroku. I am using node.js. This is my code:

if (req.body.isAdmin === 1) {
      connection.query(
        `SELECT * FROM admin WHERE username='${req.body.username}' AND password='${req.body.password}'`,
        function (err, rows) {
          if (!err) {
            console.log(rows);
            res.status(201).json({
              success: true,
              message: "Admin Logged In!",
            });
          } else {
            res
              .status(404)
              .json({ success: false, message: "Admin Not Found!" });
          }
        }
      );
    } else {
      connection.query(
        `SELECT * FROM guard WHERE username='${req.body.username}' AND password='${req.body.password}'`,
        function (err, rows) {
          if (!err) {
            console.log(rows);
            res.status(201).json({
              success: true,
              message: "Guard Logged In!",
            });
          } else {
            res
              .status(404)
              .json({ success: false, message: "Guard Not Found!" });
          }
        }
      );
    }
  } catch (error) {
    res.status(500);
    throw new Error(error);
  }

In the above code, i first check whether the user is an admin or not, then i execute the respective query. The db connects properly i.e., there is no issue with the db connection.

The issue is that there is no output for any of the queries i.e., rows variable is empty. Even if the data is false and doesn't match the data available, it doesn't give an error and also doesn't give an output. I have double-checked the connection and the query and they seem fine. I don't get where the issue is. Please help!

Mushood Hanif
  • 501
  • 1
  • 5
  • 17
  • Query not returning rows and having an error while querying a database are two different things. You need to check the number of rows returned to determine if a user is an admin or not. – Shadow May 03 '22 at 12:54
  • @Shadow there exists data in the database, and if the query is right, i should get an output. If the query has an issue or there is any kind of error, an error should be displayed. The issue is, no matter what the scenario, i don't get an error or data in return. – Mushood Hanif May 03 '22 at 12:59
  • If the rows variable is empty, then your search conditions do not match any rows. I cannot tell you why that happens - you need to do your debugging and see if there is something wrong with the parameters you are passing to the sql query! – Shadow May 03 '22 at 14:18

0 Answers0