I'm setting up a database using phpMyAdmin. I have two tables (foo
and bar
), indexed on their primary keys. I am trying to create a relational table (foo_bar
) between them, using their primary keys as foreign keys.
I created these tables as MyISAM, but have since changed all three to InnoDB, because I read that MyISAM doesn't support foreign keys. All id
fields are INT(11)
.
When I choose the foo_bar
table, click the "relation view" link, and try to set the FK columns to be database.foo.id
and database.bar.id
, it says "No index defined!" beside each column.
What am I missing?
For the sake of simplicity, I want to keep using phpMyAdmin. I am currently using XAMPP, which is easy enough to let me focus on the PHP/CSS/Javascript, and it comes with phpMyAdmin.
Also, although I haven't been able to set up explicit foreign keys yet, I do have a relational table and can perform joins like this:
SELECT * FROM foo INNER JOIN foo_bar ON foo.id = foo_bar.foo_id INNER JOIN bar ON foo_bar.bar_id = bar.id;
It just makes me uncomfortable not to have the FKs explicitly defined in the database.
You can set a primary key on a text column. In phpMyAdmin, display the Structure of your table, click on Indexes, then ask to create the index on one column. Then choose PRIMARY, pick your TEXT column, but you have to put a length big enough so that its unique.
Here's the syntax to create foreign key in MySQL. ALTER TABLE table_name ADD CONSTRAINT constraint_name FOREIGN KEY (foreign_key_name,...) REFERENCES parent_table(column_name,...); In the above query, table_name is the the table where you want to add foreign key.
If you want to use phpMyAdmin to set up relations, you have to do 2 things. First of all, you have to define an index on the foreign key column in the referring table (so foo_bar.foo_id, in your case). Then, go to relation view (in the referring table) and select the referred column (so in your case foo.id) and the on update and on delete actions.
I think foreign keys are useful if you have multiple tables linked to one another, in particular, your delete scripts will become very short if you set the referencing options correctly.
EDIT: Make sure both of the tables have the InnoDB engine selected.
phpMyAdmin lets you define foreign keys using their "relations" view. But since, MySQL only supports foreign constraints on "INNO DB" tables, the first step is to make sure the tables you are using are of that type.
To setup a foreign key so that the PID column in a table named CHILD references the ID column in a table named PARENT, you can do the following:
By doing an export on the CHILD table, you should see a foreign key constraint has been created for the PID column.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With