SQLite:last_insert_rowid()在同一个INSERT语句中

时间:2015-02-17 21:30:17

标签: php mysql sqlite pdo sql-insert

我在PHP / SQLite 3(PDO)中运行此查询

场景:新的驱动程序插入到驱动程序表中,现有的汽车立即与他链接:

DRIVERS

  • driver_id [PK]
  • DRIVER_NAME

CARS

  • car_id [PK]
  • fk_driver_id [FK]

    $ qr =" INSERT INTO drivers(driver_name)VALUES(' {$ _ GET [' driver_name']}');承诺; UPDATE汽车SET fk_driver_id =(SELECT last_insert_rowid())WHERE car_id = {$ _ GET [' car_id']};&#34 ;; $ stmt = $ dbh-> prepare($ qr); $ result = $ stmt-> execute();

它插入了驱动程序,但没有更新cars表并且也没有产生错误。

如果我使用SQLite Spy使用相同的查询,它会起作用。

在PHP中,只有我将其分为两部分才能实现:

$qr = "INSERT INTO drivers (driver_name) VALUES ('{$_GET['driver_name']}'); COMMIT; ";
$stmt = $dbh->prepare($qr);
$result = $stmt->execute();

$qr = "UPDATE cars SET fk_driver_id=( SELECT last_insert_rowid() ) WHERE car_id={$_GET['car_id']};";
$stmt = $dbh->prepare($qr);
$result = $stmt->execute();

如果PHP代码不能在单个语句中工作,那么PHP代码有什么问题?

1 个答案:

答案 0 :(得分:0)

尝试这种方式:

$qr = "INSERT INTO drivers (driver_name) VALUES ('{$_GET['driver_name']}'); ";
$stmt = $dbh->prepare($qr);
$result = $stmt->execute();
$lastId = $dbh->lastInsertId();
$dbh->commit();

$qr = "UPDATE cars SET fk_driver_id=? WHERE car_id={$_GET['car_id']};";
$stmt = $dbh->prepare($qr);
$result = $stmt->execute(array($lastId));