简体   繁体   中英

How to generate next auto increment number in mysql using php?

I was trying to fetch next auto increment number in mysql using php. I tried this way:

<?
$q=mysql_query("SELECT * FROM `users`");
$next_auto_inc=mysql_num_rows($q)+1;
?>

But, this when any row is deleted don't work. I hope you got what I mean. How can I do this using php?

You can't do that fetching the table data. You have to fetch the table status to get the auto increment number using php. And that, you can do something like this:

$q = mysql_query("SHOW TABLE STATUS LIKE 'test'");
$row = mysql_fetch_assoc($q);
$next_increment = $row['Auto_increment'];
echo "next increment number: [$next_increment]";

Hope this helps :)

[ Source ]

Assuming that you have user_id column as primary key you can also try this:

$q = mysql_query('SELECT MAX(user_id) as user_id from `users`');
$row = mysql_fetch_assoc($q);
$next_auto_inc = $row['user_id'] + 1;

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