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 |
+----+---
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";
Shortest possible code seems to be something like
// $dblink contain database login details
// $tblName the current table name
$r = mysqli_fetch_assoc(mysqli_query($dblink, "SHOW KEYS FROM $tblName WHERE Key_name = 'PRIMARY'"));
$iColName = $r['Column_name'];
SELECT k.column_name
FROM information_schema.key_column_usage k
WHERE k.table_name = 'YOUR TABLE NAME' AND k.constraint_name LIKE 'pk%'
I would recommend you to watch all the fields
use:
show columns from tablename where `Key` = "PRI";
If you want to generate the list of primary keys dynamically via PHP in one go without having to run through each table you can use
SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.key_column_usage
WHERE table_schema = '$database_name' AND CONSTRAINT_NAME = 'PRIMARY'
though you do need to have access to the information.schema to do this.
MySQL has a SQL query "SHOW INDEX FROM" which returns the indexes from a table. For eg. - the following query will show all the indexes for the products table:-
SHOW INDEXES FROM products \G
It returns a table with type, column_name, Key_name, etc. and displays output with all indexes and primary keys as -
*************************** 1. row ***************************
Table: products
Non_unique: 0
Key_name: PRIMARY
Seq_in_index: 1
Column_name: product_id
Collation: A
Cardinality: 0
Sub_part: NULL
Packed: NULL
Null:
Index_type: BTREE
Comment:
Index_comment:
To just display primary key from the table use :-
SHOW INDEXES FROM table_name WHERE Key_name = 'PRIMARY'