1

I want to check if some date exist in a table, if not I want to insert it. I have done this in other project and there it works but now i don't know why it doesn't work.

var mysql = require('mysql');
var connection = mysql.createConnection({
   host     : '',
   user     : '',
   password : '',
   database : ''
});

[..]

connection.query('SELECT id FROM users [...]', function(err, results) {
    if (err) {
         throw err;
    } else if (results.length==1) {
         callback(null, results[0].id);
    } else {
         console.log('before insert');
         connection.query('INSERT INTO users SET ?', user, function(err, result) {
             console.log('insert');
             if (err) throw err;
         });
    }
});

The query with INSERT doesn't work, but if i get that query out of the SELECT query then it works. Doesn't matter if it is INSERT or other query. In console I only see: 'before insert' and no error. This query it's in a loop.

1
  • 1
    Insert syntax is : insert into t (col1, col2) values (?, ?) Commented Aug 6, 2014 at 10:01

1 Answer 1

2

You have syntax error in insert statement, it has to be:

 connection.query('INSERT INTO users (`id`) VALUES (?)', user, function(err, result) {
     console.log('insert');
     if (err) throw err;
 });

You could also optimise the code to run a single query only, using INSERT IGNORE syntax. If record already exists, MySQL will just ignore the insert, without giving any errors. But your field id has to be set as primary key.

Optimised, the code will look like:

var mysql = require('mysql');
var connection = mysql.createConnection({
   host     : '',
   user     : '',
   password : '',
   database : ''
});

[..]
connection.query('INSERT IGNORE INTO users (`id`) VALUES (?)', user, function(err, results) {
    if (err) {
         throw err;
    } else {
         callback(null, user);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.