简体   繁体   中英

Not able to output the last auto-generated ID in php

I am trying to output the insert ID of an item that I am adding to a table.

I have tried using $result -> insert_ID to get the auto-generated ID, but it simply does not work.

<?php
require_once 'login.php' ; //my log file
$conn = new mysqli($hn, $un, $pw, $db) ; 
if ($conn->connect_error) die($conn-> connect_error);

$table = "cats"; //table we get data from

$query = "INSERT INTO $table VALUES(NULL, 'Lynx', 'Stumpy', 5)"; //this is the item we're inserting
$result = $conn ->query($query); //stores output of query into $result
$insertID = $result-> insert_ID; //should retrieve last auto-gen ID
if (!$result) die("Database access failed: " . $conn->error); 

echo "The Insert ID was: " . $insertID ; //should print "The Insert ID was: ##"
?>

Instead it just prints "The Insert ID was: ". This is an example that I am following from Robin Nixon's Learning PHP, MYSQL & JavaScript book. I have even tried copying and pasting his example into eclipse to see if I just have a syntax error somewhere, but his code resulted in the same output.

I actually just figured it out. insert_id is a property of mysqli objects, so

$insertID = $conn->insert_id

actually retrieves the ID.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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