Search code examples
phpfunctioninsertpdouser-registration

create new if already exists PHP


I am creating a random user ID, but I would like to check if the ID already has been used (very unlikely but the chances are there), but somehow this doesn't work. When I look in the database, there is no random character string in the account_id field. Do I call the functions in a wrong way?

function genRandomString() {
    $length = 40;
    $characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";    
    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }
    return $string;
}

function createID() {
    $cl_id = 'h_u_'.genRandomString();
}   

createID();

$sql_query="SELECT * FROM accounts WHERE account_id = :cl_id";
$statement = $conn->prepare($sql_query);
$statement->bindParam(':cl_id', $cl_id, PDO::PARAM_STR);    
if ($statement->execute() && $row = $statement->fetch())
    {
        createID();
    }

$conn->exec("INSERT INTO accounts SET  
            account_id='$cl_id' ,
            name='$_POST[name]' ,
            email='$_POST[email]' ");   

Solution

  • $cl_id is a local variable in createID() function , you need to return your value to your global code ...

    function createID() {
    return $cl_id = 'h_u_'.genRandomString();
    }   
    

    you need to check $id in the main code

    $id = createID();
    $sql_query="SELECT * FROM accounts WHERE account_id = '".$cl_id."'";
    $statement = $conn->prepare($sql_query);