我试图生成随机代码,并插入数据库 我想生成其他随机代码(如果存在于数据库中)
这是我的随机课程:
<?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();
?>
这里检查&amp;打印代码
$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;
}
答案 0 :(得分:1)
请查看下面的代码段。您将能够使用它创建唯一的随机代码。如果您有任何疑问,请告诉我。
<?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);
?>