生成唯一订单ID

时间:2016-11-07 23:20:56

标签: php mysql

我试图生成一个唯一的订单ID。我已经有了一些代码,但我无法验证订单是否已存在。

<?php
$exists = 1;   
while($exists > 0) {

    $store = "TLP"; //This one is just to appear before the random number Those are like the initials of the shop
    $orderid = substr(str_shuffle('0123456789'), 0, 3);
    $exists = $this->count_rows('tblorders', "WHERE oder_orderid=" . $store . $orderid);

    $value8 = $store . $orderid;
    echo $value8;

}?>

但是我没有从echo $value8;得到任何东西。

我只需要一种方法来验证结果$value8,如果有一个相等则生成另一个,如果没有人等于退出循环并保持$value8

$store = "TLP";
$orderid = substr(str_shuffle('0123456789'), 0, 3);
$value8 = $store . $orderid;

上面代码的结果类似TLP123,但我需要一种方法来验证我的列中是否已经TLP123,如果它在列中生成另一个。

编辑:也用这个测试但是什么都没有。

      function check_number(){

    $store = "TLP";
    $orderid = substr(str_shuffle('0123456789'), 0, 3);
    $value8 = $store . $orderid;
    $exists = $this->count_rows('tblorders', "WHERE oder_orderid='" . $store . $orderid."'");



    if ($exists >0){
        $results = check_number();
    }
     else{
            $results = $value8;
        return $results;
     }
echo $value8;

}

2 个答案:

答案 0 :(得分:1)

很抱歉迟到的回复,是在学校,我不想被抓住,但如果你仍然遇到问题,你可以这样使用PDO

$statement = "SELECT * FROM table WHERE column = 'what_id_to_search_for'";
$query     = $pdo->query($statement, PDO::FETCH_ASSOC); # FETCH_ASSOC just returns an assosiative array.
if ($query->rowCount())
{
  # The row exists! Do again! (re-call function, etc...)
} else {
  # The row doesn't exist! Woo! We can insert!
}

如果你正在使用MySQLi等...请告诉我我会删除我的答案,因为我不喜欢那种连接语言,如果这样做没有意义我可以重写它以使你更简单,

此外,我不明白你为什么不使用AUTO_INCREMENT类型,然后只设置类似TLP的类型。 : - )

祝你好运!

答案 1 :(得分:0)

变化:

$exists = $this->count_rows('tblorders', "WHERE oder_orderid=" . $store . $orderid);

为:

$exists = $this->count_rows('tblorders', "WHERE oder_orderid='" . $store . $orderid."'");
相关问题