以下似乎产生了一个无限循环,但我似乎可以弄清楚为什么它不起作用。我知道插入不起作用,但我不知道为什么。我已经在 phpmyadmin 中尝试了查询,它工作正常。
function generate_cart_id($dbh) {
//generate cart_id and check against assigned_carts to make sure it's unique
$ip=$_SERVER['REMOTE_ADDR'];
$stmt=$dbh->prepare("insert into assigned_carts (cart_id,ip,date) values (:cart_id,:ip,now())");
$stmt->bindValue(':ip',$ip, PDO::PARAM_STR);
do {
$cart_id=mt_rand(100000000,9999999999);
$stmt->bindValue(':cart_id',$cart_id, PDO::PARAM_INT);
}
while ($stmt->execute()==false);
return $cart_id;
}
这就是我最后想出的。
function generate_cart_id($dbh) {
$ip=$_SERVER['REMOTE_ADDR'];
$stmt=$dbh->prepare("INSERT INTO assigned_carts (cart_id,ip,date) Value ((select * from (SELECT FLOOR(100000000 + RAND() * 899999999) as ar From assigned_carts where 'ar' NOT IN (Select cart_id FROM assigned_carts) LIMIT 1) as x) ,:ip,now())");
$stmt->bindValue(':ip',$ip, PDO::PARAM_STR);
try {
$stmt->execute();
$id=$dbh->lastInsertID(); //You cannot retreive a randomly generated id with last id. Only an autoincremented one so I added that and used a select to get the random one.
$row=$dbh->query("select cart_id from assigned_carts where id=$id")->fetch();
return $row['cart_id'];
}
catch(PDOException $e){
// do something
return -1;
}
}