0

im trying to obtain a table name of foreign assoc in mysql with PDO. for example, i have:

users table

+------------+----------+------+-----+-----+----------------+
| Field      | Type     | Null | Key |  AI | Foreign Keys   |
+------------+----------+------+-----+-----+----------------+
| id         | int(255) | NO   | PRI | yes |                |
| username   | char(16) | NO   |     |     |                |
| password   | char(32) | NO   | UNI |     |                |
| group      | int(255) | NO   | MUL |     | mytable.group  |
| created    | datetime | NO   |     |     |                |
+------------+----------+------+-----+-----+----------------+

group table

+------------+----------+------+-----+-----+----------------+
| Field      | Type     | Null | Key |  AI | Foreign Keys   |
+------------+----------+------+-----+-----+----------------+
| id         | int(255) | NO   | PRI | YES |                |
| name       | char(16) | NO   | UNI |     |                |
| description| TEXT     | YES  |     |     |                |
+------------+----------+------+-----+-----+----------------+

I want to obtain the name of foreign table assoc(users.group => group ) dinamically. SHOW COLUMNS and DESCRIBE commands doesnt show a assoc.

If anyone knows how to do it I will be very grateful. Thanks!

1
  • Why was that down voted?, because i correctly answer a hard question? This makes no sense.
    – Stefan Luv
    Aug 22, 2012 at 19:29

2 Answers 2

4

SHOW CREATE TABLE users, shows all the info of the table, but not in an organized array. I found a method to obtain all assoc data dynamically with SQL:

SELECT 
      ke.column_name col, 
      ke.referenced_table_schema assoc_db,
      ke.referenced_table_name assoc_table,
      ke.referenced_column_name assoc_col
FROM
      information_schema.KEY_COLUMN_USAGE ke
WHERE
      ke.referenced_table_name IS NOT NULL              
AND   ke.table_schema='YOUR_DATABASE_NAME'
AND   ke.table_name='YOUR_TABLE_NAME'

My example will return:

array(
      public 'col' => string 'group' (length=5) //field with foreign data
      public 'assoc_db' => string 'mytable' (length=6)  //foreign db 
      public 'assoc_table' => string 'group' (length=5) //foreign table
      public 'assoc_col' => string 'id' (length=2) //foreign field
);
2

Try this:

SHOW CREATE TABLE users
1
  • 1
    SHOW CREATE TABLE users, shows all the info of table, but not in organized array.
    – Stefan Luv
    Aug 21, 2012 at 23:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.