0

How to get the id of the last inserted query using prepared statement ?

I wrote some PHP but I only get "0" as a result. I tried to use the answer from this question : Similar question on SO

$locationName = $_GET['locationName'];
$locationResume = $_GET['locationResume'];

$sql = "INSERT INTO location (locationTitle, locationResume) VALUES (?,?);";
if ($locationName != null && $locationResume != null ) {

    if ($stmt = $con->prepare($sql)) {
        $stmt->bind_param("ss", $locationName, $locationResume);
        $locationId = $con->insert_id;

        #$locationId = $con->execute();
        echo $locationId;
    }
}

Thank you for your help.

Community
  • 1
  • 1
Fundhor
  • 3,369
  • 1
  • 25
  • 47
  • 2
    You can get last_insert_id only after query execution. – vuliad Jan 15 '17 at 23:37
  • 1
    You never execute so there is nothing inserted. When in doubt see the manual, http://php.net/manual/en/mysqli.insert-id.php. – chris85 Jan 15 '17 at 23:40
  • @vuliad Thank you, I thought it executed at the same time.. (like mysqli_insert_id()) You can post an an answer, I'll accept. – Fundhor Jan 15 '17 at 23:41

1 Answers1

5

You can get last_insert_id only after query execution.

vuliad
  • 2,142
  • 3
  • 15
  • 16