Tuesday, 30 May 2017

How to make a Do-While loop with a MySQL connection to validate unique number using callbacks

I´m been breaking my head thinking how to make a do/while statement.

What I´m doing is creating a unique number for identify the user (it´s not the ID of the table) in my table users, then I need to search in the table to see if that number it´s not already taken with a do/while, if it´s already taken then create a new one and also validate it, if it´s not taken then continue, here is my code:

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

var get_ID = () => {

  return Math.floor(Math.random() * 99999999) + 10000000;

}

function exist_ID(ID, callback){

  var query = 'SELECT IF(COUNT(*) > 0, "TRUE", "FALSE") AS RESULT FROM USERS WHERE USER_NUMBER = ' + ID + '';

    connection.query(query, function (error, results) {

        if (error) throw error;

        callback(results[0].RESULT);

  });

  connection.end();

}

var ID = get_ID();

exist_ID(ID, function(answer){

  do{

    ID = get_ID();

    //?

  }while(answer);

});



via jorge tirado

No comments:

Post a Comment