以下似乎產生了一個無限循環,但我似乎找出爲什麼它不起作用。我知道該插入不工作,但我不明白爲什麼。我已經在phpmyadmin中試過了這個查詢,它工作正常。PHP PDO插入失敗導致無限循環
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;
}
}
你的循環是倒退。它終止於成功(良好),但繼續執行失敗(錯誤)。如果查詢失敗,則再次嘗試查詢,失敗,再次運行,等等等等等等。 –
這就是它想要做的。它在重複行上失敗,因此它會嘗試另一個cart_id。 – Codeguy007
出於好奇,爲什麼不使用SELECT語句來獲取所有cart_id,然後使用PHP生成不在該列表中的cart_id?這應該更有效率。 –