Search code examples
mysqlnode.jsrecordexists

NodeJS Check if record exists


I have a little trouble with my script.

if (msg.indexOf('!addcom') === 0) {
            if (typeof args[1,2] !== 'undefined' && args[1].trim() !== '') {
                if(_.indexOf(modlist, user.username) >= 0) {
                    msg.split(" ");
                    check = connection.query('SELECT 1 FROM commands WHERE channel = "'+channel+'" AND command = "'+args[1]+'"');
                    args[2] = args.slice(2).join(" ");
                        if (check === null) {
                            connection.query('INSERT INTO commands (channel, command, message) VALUES ("'+channel+'","'+args[1]+'","'+args[2]+'")');
                        }
                        else if (check === 1) {
                            client.say(channel, "Der Befehl " +args[1]+ " existiert bereits!");
                        }
                        else {
                            client.say(channel, "Ein Fehler ist aufgetreten!");
                        }
                }
                else {
                    client.say(channel, user.username+", du bist kein Moderator und kannst diesen Befehl daher nicht ausführen!");
                }
            }
            else {
                client.say(channel, "Syntax Fehler: !addcom [!Befehl] [Nachricht]");
            }
        }

I want to check if there is already a record for channel = "'+channel'" AND command = "'args[1]'" because they're unique together but for some reason it wont work properly.

Either it crashes because of duplicate entry or it just jumps to the last else clause else { client.say(channel, "Ein Fehler ist aufgetreten!"); }

Does anyone know where I made a mistake?

Sincerely Kazuto


Solution

  • The MySQL query is not synchronous/blocking. You need to pass a callback to query() and move the logic after the query inside that callback. Take a look at the first example in the mysql readme.