天天看点

mysql获取表主键字段_如何从mysql表中获取自动递增字段名称或主键字段名称?...

mysql获取表主键字段_如何从mysql表中获取自动递增字段名称或主键字段名称?...

In PHP, how do I get the field name of the field that's been set as to auto increment when a new rec is added to it?

In most cases, it's the same as the PRIMARY_KEY of the table but not necessarily always.

So this question has 2 parts with the second one branching into a 3rd part.

1- How to get the name of the auto-incrementing field name...

2- How to get the name of the primary_key field name...

2.1 How to get the primary_key(s) info when a table uses more than one field as its primary key...

解决方案

You can get the table information using the SHOW COLUMNS FROM table. Something like this:

$res = $mysqli->query('SHOW COLUMNS FROM tablename');

while($row = $res->fetch_assoc()) {

if ($row['Extra'] == 'auto_increment')

echo 'Field with auto_increment = '.$row['Field'];

if ($row['Key'] == 'PRI')

echo 'Field with primary key = '.$row['Field'];

}