Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the Foreign Keys with PHP

I'm creating a class in PHP where I just have the parameter of the Table Name and fetch all the Columns and Values. But I don't know how get the values of the Columns with Foreign Keys.
That's because I don't know to which table is related.

I need a way that I can get the Foreign Key with PHP or SQL from a known table?

like image 302
Iza_U Avatar asked Sep 24 '26 19:09

Iza_U


1 Answers

In MySql, you can query the information_schema to get meta information about the database.

SELECT
  TABLE_NAME AS `table_name`,
  COLUMN_NAME AS `column_name`,
  REFERENCED_COLUMN_NAME AS `referenced_column_name`,
  REFERENCED_TABLE_NAME AS `referenced_table_name`
FROM information_schema.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = DATABASE()
  AND REFERENCED_TABLE_SCHEMA = DATABASE()

From: https://github.com/troelskn/pdoext/blob/master/lib/pdoext/connection.inc.php#L413 (Specifically the loadKeys function)

like image 103
troelskn Avatar answered Sep 26 '26 10:09

troelskn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!