猿问

php mysql类别子类别列表链接

我想喜欢这个

类别1

--subcat1

--subcat2

类别2

--subcat2

我有两个表 tbl_cat 和 tbl_subcat

tbl_cat(id,cat_name)

tbl_subcat(id, cat_id ,subcat_name)

cat_id=tbl_cat.id

如何编写函数并显示类别和子类别链接


哆啦的时光机
浏览 70回答 1
1回答

慕神8447489

你可以这样做。测试数据:create table tbl_cat (id int, cat_name varchar(32));insert into tbl_cat(id, cat_name) values(1, "category1"), (2, "category2");create table tbl_subcat (id int, cat_id int, subcat_name varchar(32));insert into tbl_subcat(id, cat_id, subcat_name) values(1, 1, "subcat11"), (2, 1, "subcat12"), (3, 1, "subcat13"), (4, 2, "subcat21");然后,PHP 脚本可以这样写:<?php&nbsp;$servername = "localhost";$username = "your_user";$password = "your_password";$dbname = "test";// Create connection$conn = new mysqli($servername, $username, $password, $dbname);// Check connectionif ($conn->connect_error) {&nbsp; &nbsp; die("Connection failed: " . $conn->connect_error);}$sql = "SELECT cat_name, subcat_name FROM tbl_cat LEFT JOIN tbl_subcat ON tbl_cat.id = tbl_subcat.cat_id;";$result = $conn->query($sql);$last_category = "";if ($result->num_rows > 0) {&nbsp; &nbsp; // output data of each row&nbsp; &nbsp; while($row = $result->fetch_assoc()) {&nbsp; &nbsp; &nbsp; &nbsp; $cat_name = $row["cat_name"];&nbsp; &nbsp; &nbsp; &nbsp; if ($cat_name != $last_category) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo "Category: " . $cat_name .PHP_EOL;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $last_category = $cat_name;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; echo "\tSubcategory: " . $row["subcat_name"] .PHP_EOL;&nbsp; &nbsp; }} else {&nbsp; &nbsp; echo "0 results";}$conn->close();?>&nbsp;
随时随地看视频慕课网APP
我要回答