Mahmoud Mohmed Mahmoud Mohmed - 4 months ago 11
MySQL Question

check if value exist in db and return other value if exist

i'm trying to generate random code , and insert into database
i want to generate other random code if exist in database

this my random class :

<?php
class code {
public $code;
public function mycode(){

$this->code = rand(1111111,9999999); //7894564

$this->code = str_replace(0,"A",$this->code);
$this->code = str_replace(1,"B",$this->code);
$this->code = str_replace(2,"-",$this->code);
$this->code = str_replace(3,"C",$this->code);
$this->code = str_replace(4,"I",$this->code);
$this->code = str_replace(5,"GB",$this->code);
$this->code = str_replace(6,"7",$this->code);
$this->code = str_replace(7,"W4",$this->code);
$this->code = str_replace(8,"S",$this->code);
$this->code = str_replace(9,"M",$this->code);
$this->code = str_replace(10,"RQ",$this->code);

$this->code = substr($this->code,0,9);

return $this->code;

}
}

$class_code = new code();
?>


here check & print code

$code = $class_code->mycode();
$get_code = mysqli_query($link,"Select * from links WHERE link = '".$code."'");
$if_exist = mysqli_num_rows($get_code);
if($if_exist == 1)
{
while($if_exist == 1)
{
// Here Return New Code
}
} else{
echo $code;
}

Answer

Please check below snippet. You will able to create unique random code using it. If you have any query please let me know.

<?php 
class code {
    public $code;
    public function mycode($link,$length=6){
        //Generating random code
        $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $this->code = '';
        for ($i = 0; $i < $length; $i++) {
        $this->code .= $characters[rand(0, strlen($characters) - 1)];
        }
        //Check generated code is exist in Db or not
        $get_code =  mysqli_query($link,"Select * from links WHERE link = '".$this->code."'");
        $if_exist = mysqli_num_rows($get_code);
        if($if_exist == 1)
        {
            //if code is already exist then recursively call function to generate new unique code.
            $this->mycode($link);
        }
        return $this->code;
    }
}
//create object
$class_code = new code();
//call function to generate unique code.
//$link is the connection
$uniqueCode = $class_code->mycode($link);
?>
Comments