Reputation: 3
I can't see what I did wrong, please help. I'm learning about Select Last_Insert_Id
and I've been stuck for a few days now.
$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");
}
Upvotes: 0
Views: 174
Reputation: 897
I am supposing that you might be inserting recording, then only you can get last inserted ID. There are 2 ways you can achieve it,
After inserting get last inserted value. This is how you can do it
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]')";
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);
}
I am expecting that you are having atleast primary key to pull out unique records from table so, this is how you can get last id, by applying order by descending.
`
$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";
}
`
Upvotes: 2
Reputation: 435
you can get the last_insert_id by doing like this
$last_id = $conn->insert_id;
For more Info: https://www.w3schools.com/PHP/php_mysql_insert_lastid.asp
Or You can do this way too
$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;
Upvotes: 0