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
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.
- 热议问题