0

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

2 回答 2

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.
}

好读

MySQL 开发人员的 PDO 教程

于 2012-11-04T05:25:53.787 回答
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;
}
于 2012-11-04T05:40:05.110 回答