Jump to content

Generate value that doesn't exist in table


adamrcarlson

Recommended Posts

I'm generating a nine digit pseudo-random number to be inserted into a database table with mysqli where the code inserted doesn't already exsit, and I just wanted to check with someone to see if this is an okay way of doing so.

function generateNewCode($a_con){

    $report = rand(100000000, 999999999);
		
    $code_string = "SELECT code_number FROM Codes WHERE code_number = " . $new_code;

    $code_result = mysqli_query($a_con, $code_string);
		
    while(mysqli_num_rows($code_result) >= 1){
			
        $report = rand(100000000, 999999999);
		
    }
		
    return $report;

}

Technically this could run forever, if the generated number continuously matches... But I don't know how else to avoid that.

Running queries within loops is not very efficient. You could select all codes from the database and then add them to an array. Then use PHP to loop through that array checking to see if the new code exists, if does regenerate the code and check again. Only add the code to the database when the code doesn't match.

 

Something like

function getCodes()
{
    $code_string = "SELECT code_number FROM Codes";
    $code_result = mysqli_query($a_con, $code_string);

    $codes = array();
    while($row = mysqli_fetch_assoc($code_result))
    {
        $codes[] = $row['code_number'];
    }

    return $codes;
}


function generateNewCode($codes){
 
    // generate code
    $report = rand(100000000, 999999999);
    
    // check that it exists
    if(in_array($report, $codes))
        return generateNewCode($codes); // it exists, call this function again, generates a new code
    else
        return $report; // Code doesn't exist, return the generated code
}

$codes = getCodes(); // get codes from database
$report = generateNewCode(&$codes); // generate a code

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.