PHP/MySQL - Best way to create unique random string?

后端 未结 10 2121
囚心锁ツ
囚心锁ツ 2020-12-15 04:20

How do I create a random unique string in MySQL?

when I need to create a random string in PHP I use this function:

public function generateString($le         


        
10条回答
  •  南方客
    南方客 (楼主)
    2020-12-15 04:55

    I would make the column of this id unique in your DB. Then you can do something like this to safeguard against collisions:

        $row_count = 0;
        while ($row_count == 0) {
            error_reporting(0);
            $id_string = substr(uniqid(), 0, 10);
    
            $sql = "UPDATE  SET unique_id = :unique_id WHERE ";
            $query = $this->db->prepare($sql);
            $query->execute(array(':unique_id' => $unique_id));
            $row_count = $query->rowCount();
        }
    
    
    

    Sure, it may need to try the query more than once, but this way you know it's guaranteed to be unique in your DB. The error_reporting(0) line is in there to suppress any warnings which might be turned on. PHP's uniqid() also isn't the most unique generate there is, but you can easily swap that out for your own or just take the hit of potential collisions here and there.

    提交回复
    热议问题