views:

595

answers:

6

Hello!

Is there a way to get the name of primary key field from mysql-database? For example:

I have a table like this:

+----+------+
| id | name |
+----+------+
| 1  | Foo1 |
| 2  | Foo2 |
| 3  | Foo3 |
+----+------+

Where the field id is primary key (it has auto increment but I can't use that). How can I retrieve fields name "id" in php?

Martti Laine

+4  A: 

Here is the Primary key Column Name

SELECT k.column_name
FROM information_schema.table_constraints t
JOIN information_schema.key_column_usage k
USING(constraint_name,table_schema,table_name)
WHERE t.constraint_type='PRIMARY KEY'
  AND t.table_schema='YourDatabase'
  AND t.table_name='YourTable';
Svetlozar Angelov
yes - this is one way. In the MySQL case, you can even simplify this, because the constraint_name will always be `PRIMARY`
Roland Bouman
I choosed this because this works and was posted earlier.
Martti Laine
A: 

I think if you fetch data from your database the primarykey is already in it access it like $yourdatabase->id; I dont know which method you trying to fetsch the datas but the primary key is also in that datas. Access it with id

streetparade
+2  A: 
SELECT kcu.column_name
FROM   information_schema.key_column_usage
WHERE  table_schema = schema()             -- only look in the current db
AND    constraint_name = 'PRIMARY'         -- always 'PRIMARY' for PRIMARY KEY constraints
AND    table_name = '<your-table-name>'    -- specify your table.
Roland Bouman
+2  A: 

A better way is to use SHOW KEYS since you don't always have access to information_schema. The following works:

SHOW KEYS FROM table WHERE Key_name = 'PRIMARY'

Column_name will contain the name of the primary key.

alexn
Good suggestion. information_schema is supported as of MySQL 5.0, but indeed this method works for even older versions too.
Roland Bouman
+1  A: 

For a PHP approach, you can use mysql_field_flags

$q = mysql_query('select * from table limit 1');

for($i = 0; $i < mysql_num_fields(); $i++)
    if(strpos(mysql_field_tags($q, $i), 'primary_key') !== false)
        echo mysql_field_name($q, $i)." is a primary key\n";
Benoit Vidis
yup, good suggestion. although limited, this is a good enough for the primaruy keys.
Roland Bouman
A: 

Is there any code for getting Primary Key from ODBC (Access)???? I tried odbc_primarykeys() not working for Access... Any other option?????????

Stylus
I have tried ,odbc_exec("SHOW KEYS FROM table WHERE Key_name = 'PRIMARY'"); and its not working
Stylus