Get next auto increment

青春壹個敷衍的年華 提交于 2019-12-21 04:22:12

问题


I know this isn't so complicated but I can't remember how to do.

I just need to know the next auto increment.

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

...but i won't work for me, what am I doing wrong?


回答1:


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

The name of the table needed to be wrapped with single quotes like this: 'table_name'

So it works just fine now.

:)




回答2:


The query should look like this:

SHOW TABLE STATUS WHERE `Name` = 'Media';



回答3:


Another way, but slow, is:

SELECT AUTO_INCREMENT FROM information_schema.`TABLES` T where TABLE_SCHEMA = 'myScheme' and TABLE_NAME = 'Media';

The information_schema is mostly usefull for getting data from many schemes.




回答4:


You can also use this function

function getNextValue(){
$query = "SHOW TABLE STATUS LIKE 'vendors'";
dbconnect();
$results=mysql_query($query);
if(mysql_errno() != 0) {
    $result['count'] = -1;
    $result['error'] = "Error: ".mysql_error();
} else {
    $result['count'] = mysql_num_rows($results);
    for($counter=0;$counter<$result['count'];$counter++) {
        $result[$counter] = mysql_fetch_assoc($results);
    }
}
return $result[0]['Auto_increment'];
mysql_close();
}



回答5:


if you need to know the next auto_increment, then it's 99% likely you're doing it wrong. instead of the getting the next auto_increment, you should just do the insert you're about to do, then use SELECT LAST_INSERT_ID() to get the auto_increment value from that insert.

if you try to guess the next auto_increment value and you have multiple users doing it at the same time, you'll frequently get the wrong value.



来源:https://stackoverflow.com/questions/1372077/get-next-auto-increment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!