Get the Foreign Keys with PHP

foreign-keys, innodb, mysql, php, relational-database

Solution

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)

Problem

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?

Original source