user1476432
user1476432

Reputation:

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?

Upvotes: 1

Views: 10436

Answers (2)

Code Prank
Code Prank

Reputation: 4250

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;

Upvotes: 1

LIGHT
LIGHT

Reputation: 5712

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]

Upvotes: 2

Related Questions