I am developing a PHP web based data entry tool with MySQL as the database. However the database will undoubtedly change whilst the data entry is going on (there is a lot of it to be done so we have started it so that it runs in parallel to the other development).
I have constructed the SQL queries so that the php can automatically:
- Determine what tables are in the database
- List tables with a certain prefix so that only ones that data entry should use are listed
However, what I cant figure out (despite checking php, sql and mysql manuals and tutorials) is how to automatically pull tables that are connected by foreign key, so that data entry have a list of items to choose from for the given table. So in short, how do I – using php – determine:
- Any foreign keys for the given table
- The table name that the foreign key points to
WITHOUT hard-coding any table names into the SQL queries?
A quick way to list your Foreign Key references using the KEY_COLUMN_USAGE view:
This query does assume that the constraints and all referenced and referencing tables are in the same schema.
For InnoDB tables, using the Comment field of
SHOW TABLE STATUSis useful for extracting foreign key information for older versions of MySQL.I am unaware of any other way than the above 2 methods.
Happy coding!