[英]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.