user3733831
user3733831

Reputation: 2926

How I get next auto-increment ID in mysql table?

I need to get next auto-increment ID from my mysql product Table.

This is how I tried it:

SELECT `auto_increment` 
FROM INFORMATION_SCHEMA.TABLES
WHERE table_name = 'products';

When this query is running, I can get an output like this.

+----------------+
| auto_increment |
+----------------+
|             10 |
|              1 |
|             14 |
+----------------+
3 rows in set (0.02 sec)

Can anybody tell me why it shows 3 values. (3 rows)

NOTE: my product table is still empty.

mysql> select * from products;
Empty set (0.00 sec)

Upvotes: 2

Views: 8832

Answers (2)

ARIF MAHMUD RANA
ARIF MAHMUD RANA

Reputation: 5166

Run this query

SHOW TABLE STATUS LIKE 'products'

Using php

$result = mysql_query("
    SHOW TABLE STATUS LIKE 'products'
");
$data = mysql_fetch_assoc($result);
$next_increment = $data['Auto_increment'];

Using mysqli

$db = new mysqli('YOUR_HOST', 'DB_USERNAME', 'DB_PASSWORD', 'DATABASE');

if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}

$sql = <<<SQL
SHOW TABLE STATUS LIKE 'products'
SQL;

if(!$result = $db->query($sql)){
    die('There was an error running the query [' . $db->error . ']');
}

$row = $result->fetch_assoc();

echo $row['Auto_increment'];

Details https://stackoverflow.com/a/1372115

Upvotes: 2

Md Mahfuzur Rahman
Md Mahfuzur Rahman

Reputation: 2359

You didn't specify any database name in you query. You might have 'products' table in another database. If you don't use 'TRUNCATE' to make empty your table, the auto_increment id remains same as before. No matter that you have no data in you table.

Execute this query:

SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = "databaseName" AND TABLE_NAME = "tableName"

It will help you to find out the next auto_increment id.

Upvotes: 2

Related Questions