我有以下似乎永远运行的功能。它创建一个随机字符串,然后检查它是否在数据库中。如果是这样,它应该一次又一次地运行,直到有一个新的。然后应该将值还给我
public function checkPromo(){
$continue = true;
while ($continue){
$promo = $this->getRandString(6);
$query = sprintf("SELECT * FROM table WHERE field=%s",
$this->db->cleanCode($promo, "text"));
$result = $this->db->query($query);
if($this->db->num_rows($result) >= 1){
$continue = false;
}
}
return $promo;
}
假设您只是想生成一个未记录在数据库中的促销代码,并考虑了上下文,我建议您稍微改变一下态度:
public function generatePromo(){
$promo = $this->getRandString(6);
$query = sprintf("SELECT * FROM table WHERE field=%s", $this->db->cleanCode($promo, "text"));
$result = $this->db->query($query);
if($this->db->num_rows($result) > 0){ # in case a record with this "text" already exists, run this method again
$this->generatePromo();
} else {
return $this->promo = $promo; # otherwise return the value/store it in the object
}}
如果您希望表仅包含唯一值,那么建议您使用它UNIQUE
。这将大大减少查询时间。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句