I have been using php my admin to create a database and the time has come to display my data in my webpage.
I am struggling to display data linked to my mapping table with a foreign key.
The tables I have are:
Subcategory
subcategory_id (pk) | Subcategory name
Subsubcategory
subsubcategory_id (pk) | subsubcategory_name
Sub_subsub (mapp开发者_StackOverflow社区ing table)
id (pk) | s_id (fk) | ss_id (fk)
s_id and ss_id are foreign keys to the respective tables.
Here is the code I am playing with without any joy. Im still quite new to php
$dbc = mysql_connect($db_host,$db_user,$db_pass);
$sdb = mysql_select_db($db_database);
$query = "SELECT s_id as subcategory_id, ss_id as subsubcategory_id FROM sub_subsub";
$result = mysql_query($query, $dbc)
or die (mysql_error($dbc));
while($row = mysql_fetch_array($result)) {
$subcat = $row["s_id"];
$subsubcat = $row["ss_id"];
echo "<li>$subcat <span>$subsubcat</span></li>";
}
Im probably missing something quite obvious but I've been searching and cant find anything.
Well, in your query you give the s_id
field new name (or alias) subcategory_id
(the s_id as subcategory_id
part in the query) but in your code you still try to access it by the name s_id
. Try
$subcat = $row["subcategory_id"];
Or drop the alias from query. Similar stuff with ss_id
field.
Try something like
SELECT
SC.Subcategory_name ,
SS.subsubcategory_name
FROM Sub_subsub M
JOIN Subcategory SC ON(SC.subcategory_id = M.s_id)
JOIN Subsubcategory SS ON(SS.subsubcategory_id = M.ss_id)
to get name pairs instead of ID pairs.
BTW your table design looks somewhat suspicious... usually this kind of category hierarcy is done with only one table, something like
TABLE TAB_Category (
UID PRIMARY KEY,
Parent FK REFERENCES TAB_Category(UID) ON UPDATE CASCADE,
Name
);
where root items do have Parent = NULL.
精彩评论