Simo Simontchensé Simo Simontchensé - 6 months ago 11
PHP Question

INSERT if doesn't already exist in database

I created a function that looks for all rows (records) in a specific column,
generates a random number and then checks if it already exists withing that column, if the generated random number exists restart the function (recursive)
if it doesn't exist then insert it as new.

$verifs = mysqli_query($conlink, 'SELECT verif FROM memebers');
$records = array();
while($record = mysqli_fetch_array($verifs,MYSQLI_NUM)) {
$records[] = $record[0];
}
function randomize(){
$rand= rand(1,5);
if(in_array($rand, $GLOBALS['records'])){
randomize();
}else{
return $rand;
}
}
mysqli_query($conlink, "INSERT INTO `memebers`(`verif`) VALUES (".randomize().")");


i expected that a number MUST be added EACH time i refresh my php page

and it was the case, but when i reach 3 or 4 records, refreshing the page doesn't add any ! so the
return
statement must prevent the function from being recursive.
am i having anything wrong with my logic
thanks

Answer

It appears to me that you are not using the callback function correctly. If you didn't know, when you use a function within a function, you actually have to pass that function inside the parameters. Functions that have a function in the parameter are called callback functions and you can read more about them in the following post: What is a callback function and how do I use it with OOP

I would then change your randomize function to the following code:

function randomize($callbackRandomize){
    $rand= rand(1,5);
    if(in_array($rand, $GLOBALS['records'])){
        return $callbackRandomize($callbackRandomize);
    }else{
        return $rand;
    }
}

and also change your last line of code to:

mysqli_query($conlink, "INSERT INTO `memebers`(`verif`) VALUES (".randomize('randomize').")");

Let me know if that worked for you.