我看不到我做错了什么,请帮忙。我正在学习Select Last_Insert_Id
,现在已经呆了几天了。
$result2 = $mysqli1->query("SELECT LAST_INSERT_ID()");
while($row = mysqli_fetch_assoc($result2)) {
return $row;
}
$last_id = $row;
$sql = "UPDATE bao_admin_table SET Name='$name' WHERE ID = '$last_id' ";
if ( $mysqli1->query($sql)){
$_SESSION['message'] = 'Registration successful!';
header("location: success.php");
}else{
$_SESSION['message'] = 'Registration failed!';
header("location: error2.php");
}
答案 0 :(得分:2)
我想您可能正在插入录音,那么只有您可以获取最后插入的ID。 有两种方法可以实现它,
插入后获取最后插入的值。 这就是您可以做到的方式
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";
if (mysqli_query($conn, $sql))
{
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
我希望您拥有至少一个主键来从表中提取唯一记录,因此,这是通过递减顺序获得最后一个id的方法。
`
$sql = "SELECT * FROM MyGuests ORDER BY id DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{// output data of each row
while($row = $result->fetch_assoc())
{
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
}
else
{
echo "0 results";
}
`
答案 1 :(得分:0)
您可以通过执行以下操作来获取last_insert_id
$last_id = $conn->insert_id;
有关更多信息:https://www.w3schools.com/PHP/php_mysql_insert_lastid.asp
或者您也可以这样做
$selectquery="SELECT id FROM tableName ORDER BY id DESC LIMIT 1";
$result = $mysqli->query($selectquery);
$row = $result->fetch_assoc();
$last_id=$row['id'];
echo $last_id;