繁体   English   中英

即使持续连接,lastInsertID仍返回0

[英]lastInsertID returning 0, even with a persistent Connection

我使用函数PDO :: lastInsertID(也与mysqli_insert_id一起发生),但是它总是返回0。

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

我的表“预订”有一个主键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服务器上,插入发生后生成了一个随机字符串,现在我想通过查看最后一个插入的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');
    }

}


?>

插入行时,您需要捕获并存储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();
    }
}


?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM