NathanK NathanK - 2 months ago 8
MySQL Question

SQL & PHP Unique Number

I will be using the GET method with NFC to pull some data, I want to populate a database with a ton of unique digits, I don't mind them having keywords in them like

TOM05543
TOM04423
KEL04432
KAL43242


What would be the best method of doing this and filling my database with these unique ID's before hand?

Answer

Create a PHP function which can generate a random apha numeric code and check that code exist in DB table or not. If exist then function call recursively until unique code will be generated. And insert uniquely generated record in DB table.

<?php
//DB connection
$con=mysqli_connect("localhost","my_user","my_password","my_db");

//Function to generate unique alpha numeric code
function generateRandomNumer($con,$len=8){
    $randomString = substr(MD5(time()),$len);

    //Check newly generated Code exist in DB table or not.
    $query = "select * from table_name where col_name=".$randomString;
    $result=mysqli_query($con,$query);
    $resultCount=mysqli_num_rows($result);

    if($resultCount>0){
        //IF code is already exist then function will call it self until unique code has been generated and inserted in Db.
        generateRandomNumer($con);
    }else{
        //Unique generated code will be inserted in DB.
        mysqli_query($con,"INSERT INTO Persons (col_name) VALUES ('".$randomString."')");
    }
}

//Loop to insert number of unique code in DB.
//NUM_OF_RECORD_YOU_WANT_TO_INSERT define constant which contain number of unique codes you wants to insert in DB. 
for($i=0;$i<NUM_OF_RECORD_YOU_WANT_TO_INSERT;$i++){
    generateRandomNumer($con);
}
?>
Comments