PHP MySQL – Get Next Auto Increment Value of a Table

Posted in Web Development on 14 January 2012 1 comment

We do not often need this but sometimes when we need to retrieve the next auto increment value of a table (without incrementing the auto increment value of course), this solution below will help.

<?php
 
$query = mysql_query("SHOW TABLE STATUS WHERE name='your_table_name_here'");
if (mysql_num_rows($query)) {
	$result = mysql_fetch_assoc($query);
	echo $result['Auto_increment'];
} else {//error
	//error control here
}
 
?>

Just replace “your_table_name_here” with your mySQL table name.

As a Function

Furthermore, making it a PHP function would make the solution looks clean.

<?php
 
function get_next_value($tablename) {
	$query = mysql_query("SHOW TABLE STATUS WHERE name='".mysql_real_escape_string($tablename)."'");
	if (mysql_num_rows($query)) {
		$result = mysql_fetch_assoc($query);
		return $result['Auto_increment'];
	} else {//error
		return false;
	}
}
 
//usage
$nextval = get_next_value('your_table_name_here');
 
?>

Hope this helps.

 

Posted by Zen on 14 January 2012 • 21,198 visits 1 comment
Tags : ,


or Subscribe to specific category only :




  - 1 Comments


Bally says:

Thanks. it is very nice script

Leave a Reply

You must be logged in to post a comment.

Previous Post
«
Next Post
»