PHP PDO插入失败导致无限循环

时间:2012-11-04 05:23:06

标签: php pdo

以下似乎产生了无限循环,但我似乎可以弄清楚为什么它不起作用。我知道插入不起作用,但我无法弄清楚原因。我已经在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;
    }
}

2 个答案:

答案 0 :(得分:0)

尝试类似

的内容
if ($stmt->execute()) {
    // Query succeeded.
} else {
    // Query failed.
    $errorcode = $stmt->errorCode();
}

if ($sql->execute === false) {    //false on error
     var_dump($sql->errorinfo();  //array containing information on error
     die()
}

最佳尝试类似

的内容
function getData($db) {
   $stmt = $db->query("SELECT * FROM table");
   return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

//then much later
try {
   getData($db);
} catch(PDOException $ex) {
   //handle me.
}

好读

PDO Tutorial for MySQL Developers

答案 1 :(得分:0)

这不是严格基于PDO的解决方案,但你可以尝试这样的事情:

// grab list of all cart_id ids
$qry = 'SELECT cart_id FROM assigned_carts'
      .' WHERE cart_id >= 100000000 && cart_id <= 9999999999';
$all_cart_ids = $dbh->exec($qry);

// generate a random number that's not in that list
while($cart_id === NULL || in_array($cart_id, $all_cart_ids)){
    $cart_id=mt_rand(100000000,9999999999);
}

// insert
$stmt=$dbh->prepare("INSERT INTO assigned_carts (cart_id,ip,date) VALUES (:cart_id,:ip,now())");
$stmt->bindValue(':ip',$ip, PDO::PARAM_STR);
$stmt->bindValue(':cart_id',$cart_id, PDO::PARAM_INT);
try {
    $stmt->execute();
    return $cart_id;
}
catch(PDOException $e){
    // do something
    return -1;
}