lastInsertID返回0,即使是持久连接

时间:2017-07-12 15:49:17

标签: php mysql pdo

我正在使用函数PDO :: lastInsertID(也发生在mysqli_insert_id中),但它总是返回0。

我已经查看了问题,发现这应该可以解决问题:MySQL: LAST_INSERT_ID() returns 0 打开phpmyadmin“config.inc.php”文件中的persistentConnections,但问题仍然存在......

我的表'预订'有一个主键,即AUTO_INCREMENTs。

这是我的代码:

我的网站上有一个按钮,调用此javascript代码:

function sonderbuchung()
{
    setReservationType();
    getSonderbuchungID(); 
}


function getSonderbuchungID() {
   $.ajax({
      url:'sonderbuchungEditID.php',
      complete: function (response) {
          $('#output').html(response.responseText);
      },
      error: function () {
          $('#output').html('Bummer: there was an error!');
      }
  });
  return false;
}

function setReservationType()
{
   $.ajax({
    url: "reservationType.php",
    type: "POST",
    data: 'reservationtype=sonderbuchung',
    success: function(data) {
        $('#output').html(data);   
    },
    error: function(data) {
        $('#output').html(data.responseText)
    },  
});

}

在我的mySQL服务器上有一个随机字符串在Insert发生后生成,现在我想通过查看最后一个Inserted ID获取随机字符串并将其作为randomString。 (显然没有实现'导致这个问题')

sonderbuchungEditID.php:

<?php
require_once('bdd.php'); //Database connection
echo($bdd->lastInsertID());
?>

reservationType.php(一切正常,仅为了所有代码)

<?php
require_once('bdd.php');

if(isset($_POST['reservationtype'])){

$reservationtype = $_POST['reservationtype'];

$sql = "INSERT INTO reservations(reservationtype) values ('$reservationtype')";

$query = $bdd->prepare($sql);
if ($query == false) {
     file_put_contents('LOGname.txt', print_r($bdd->errorInfo(), true));

     die ('Error prepairing');

    }
    $sth = $query->execute();
    if ($sth == false) {
     file_put_contents('LOGname.txt', print_r($query->errorInfo(), true));
     die ('Error executing');
    }

}


?>

1 个答案:

答案 0 :(得分:0)

插入行时,您需要捕获并存储ID。

sonderbuchungEditID.php:

<?php
    echo isset($_SESSION['last_id']) ? $_SESSION['last_id'] : "-1";
?>

reservationType.php:

<?php
require_once('bdd.php');

if(isset($_POST['reservationtype'])){
    $reservationtype = $_POST['reservationtype'];
    $sql = "INSERT INTO reservations(reservationtype) values ('$reservationtype')";
    $query = $bdd->prepare($sql);
    if ($query == false) {
        file_put_contents('LOGname.txt', print_r($bdd->errorInfo(), true));
        die ('Error prepairing');
    }
    $sth = $query->execute();
    if ($sth == false) {
        file_put_contents('LOGname.txt', print_r($query->errorInfo(), true));
        die ('Error executing');
    } else {
        //  Remember the last ID inserted.
        $_SESSION['last_id'] = $bdd->lastInsertID();
    }
}


?>
相关问题