0
app.post('/addUsername', (req, res)=> {

const username = req.body.username;

db.query("SELECT * FROM userbase WHERE username = ?"), [username], (err, result)
if(result == username)
{
  db.query("INSERT INTO userbase (username) VALUE (?)", [], (err, result)=> {
    console.log(err);
   })
}
else{
  db.query("INSERT INTO userbase (username) VALUE (?)", [username], (err, result)=> 
{
    console.log(err);
  })
}

  
})

I was trying to make it so if the username exist it would not send data to the database. but I dont think I structured this correctly. Basically this database is a big list full of usernames.

Frank Ford
  • 73
  • 7
  • Why are you even sending an insert, when the username already exists? It will probably insert a NULL record the first time, and then fail for all subsequent calls, because the NULL record already exists ... Furthermore, the result of your `SELECT` will most likely be an array (even if it only has one element), so the comparison `result == username` will always fail. – derpirscher Jun 01 '21 at 06:47
  • 1
    It's worth using a database driver that supports Promises as this kind of callback-driven code can get super ugly in a hurry. Personal favorite: [Sequelize](https://sequelize.org/master/). – tadman Jun 01 '21 at 06:51
  • `VALUE (?)", []` meaning...no value? Why are you inserting if you found it? – tadman Jun 01 '21 at 06:52
  • 2
    Tip: Don't depend on checks like this, add a `UNIQUE` index constraint to prevent duplicate insertions. – tadman Jun 01 '21 at 06:52
  • In your select query, instead of select * use select count(1) FROM userbase WHERE username = ? This will always give u result either 0 or greater than 0. In case result is 0 then only insert record in other table. – Amit Verma Jun 01 '21 at 07:00
  • 1
    @AmitVerma Better, but still subject to race conditions. – tadman Jun 01 '21 at 07:05
  • 1
    Does this answer your question? [checking uniqueness when inserting and updating efficiently](https://stackoverflow.com/questions/51826738/checking-uniqueness-when-inserting-and-updating-efficiently) – danblack Jun 01 '21 at 07:39

0 Answers0