PHP PDO,SQL更新与函数" lastInsertd()"冲突

时间:2014-07-26 20:27:59

标签: php sql pdo

我在下面有这个代码,但它有一个问题:如果我调用函数' updateData()' ' getLastId()'函数返回零。注意:在函数内传递的参数' insertData()'和' updateData()'那些只是为了测试。

loggedin.php

else {

    $dataBase = new DB($db);
    $dataBase->insertData('name');
    //$dataBase->updateData('email', $dataBase->getLastId());

    if (isset($_POST['deleteAll'])) {
        $dataBase->deleteAll();
        header('Location: loggedin.php');
    }
    else if (isset($_POST['id'])) {
        $id = $_POST['id'];
        $dataBase->deleteData($id);
        header('Location: loggedin.php');
    }

    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
....

</form>

        </h5>
        <?php
        echo 'Number of visits: ' .$dataBase->getLastId().'<br><br>';
        echo 'Relevant data: ' .$dataBase->fetch_row_count().'<br><br>';
        ?>

db.php中

class DB {
protected $_db;

    public function __construct(PDO $db) {
        $this->_db = $db;
    }
function insertData($firstName) {
        $insertUser = $this->_db->prepare("INSERT INTO `people` (first_name, created) VALUES (?, NOW())");
        $insertUser->bindValue(1, $firstName);
        $insertUser->execute();
    }
function updateData($mail, $last) {
    $updateData = $this->_db->prepare("UPDATE `people` SET `mail` = ? WHERE `id` = ?");
    $updateData->bindValue(1, $mail);
    $updateData->bindValue(2, $last);
    $updateData->execute();
}

    public function getLastId() {
        $last = $this->_db->lastInsertId();
        return $last;
    }
}

1 个答案:

答案 0 :(得分:1)

根据我的测试,PDO的lastInsertId()方法显然不会在任何后续语句之后从其最新的INSERT语句返回相同的值。虽然对事务性查询很好地理解了类似行为,但未记录此行为in the lastInsertId() manual

例如,以下显示即使在中间SELECT语句之后,PDO对象也将不再返回插入的id:

$p = new PDO('mysql:host=localhost;dbname=test', '', '');
$p->query("INSERT INTO t (id) VALUES (null)");
echo $p-lastInsertId();
// prints 1

$p->query("SELECT * FROM t");
echo $p-lastInsertId();
// prints 0

这与MySQL LAST_INSERT_ID()函数的本机行为不同, 将继续在后续UPDATE或{{1}之后返回最近插入的id语句。

插入一行:

SELECT

执行中介声明:

MariaDB [test]> INSERT INTO t3 VALUES (null);
Query OK, 1 row affected (0.00 sec)

MariaDB [test]> SELECT LAST_INSERT_ID();
+------------------+
| LAST_INSERT_ID() |
+------------------+
|                6 |
+------------------+
1 row in set (0.00 sec)

该值仍然可用:

MariaDB [test]> SELECT * FROM t3;
+----+
| id |
+----+
|  3 |
|  6 |
+----+
6 rows in set (0.00 sec)

要解决您的问题,请在回显出之前的ID之后更改操作的顺序以调用MariaDB [test]> SELECT LAST_INSERT_ID(); +------------------+ | LAST_INSERT_ID() | +------------------+ | 6 | +------------------+ 1 row in set (0.00 sec) 方法,或者只将其存储到变量中以便重复使用。

updateData()