简体   繁体   中英

Fetching last inserted ID and using it as a parameter with PHP/MySQL

I'm very new to PHP, trying to figure things out.

I have the following php code:

$read_more = '<a href="http://www.example.com/index.php?id=' . mysqli_insert_id($conn)  . '" target="_self">[read more]</a>';

$sql = "INSERT INTO database (date, headline, article, read_more) VALUES ('$_POST[date]', '$_POST[headline]', '$_POST[article]', '$read_more')";

The code is returning " http://www.example.com/index.php?id=0 ". Note that the "id" parameter is returning "0". My goal is to make it return the latest ID from the database, which is set to auto increment.

I've tried many things but nothing worked for me so far. Thanks!

EDIT: After hours of trial and error, this is how I was able to solve this problem:

//After connecting to the database

$sql = "INSERT INTO table (date, headline, article, read_more) VALUES ('$_POST[date]', '$_POST[headline]', '$_POST[article]', '$read_more')";
$result = mysqli_query($conn, $sql);
$id = mysqli_insert_id($conn);

Now the latest id is saved into a variable that I can use.

Try something like this instead. Check the documentation here.

// insert a datarow, primary key is auto_increment
// value is a unique key
$query = "INSERT INTO test (value) VALUES ('test')";
mysql_query( $query );

echo 'LAST_INSERT_ID: ',
      mysql_query( "SELECT LAST_INSERT_ID()" ),
      '<br>mysql_insert_id: ',
      mysql_insert_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