CREATE TABLE IF NOT EXISTS `mytable` ( `id` int(11) NOT NULL, `parent_id` int(11) NOT NULL, `name` varchar(256) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `mytable` -- INSERT INTO `mytable` (`id`, `parent_id`, `name`) VALUES (1, 0, 'item 1'), (2, 1, 'item 2'), (3, 2, 'item 3');
And then run following script
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
ol {
margin: 0;
padding: 0;
padding-left: 30px;
}
ol.sortable, ol.sortable ol {
margin: 0 0 0 25px;
padding: 0;
list-style-type: none;
}
ol.sortable {
margin: 4em 0;
}
.sortable li {
margin: 5px 0 0 0;
padding: 0;
}
.sortable li div {
border: 1px solid #d4d4d4;
}
</style>
</head>
<body>
<ol class="sortable">
<?php
$mysql_db_hostname = "localhost";
$mysql_db_user = "";
$mysql_db_password = "";
$mysql_db_database = "";
$con = mysql_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password) or die("Could not connect database");
mysql_select_db($mysql_db_database, $con) or die("Could not select database");
function query($parent_id) { //function to run a query
$sql = "SELECT * FROM `mytable` WHERE `parent_id` = '$parent_id';";
//die($sql);
$query = mysql_query($sql);
return $query;
}
function has_child($query) { //This function checks if the menu has childs or not
$rows = mysql_num_rows($query);
if ($rows > 0) {
return true;
} else {
return false;
}
}
function fetch_menu($query) {
while ($result = mysql_fetch_array($query)) {
$id = $result ['id'];
$name = $result ['name'];
$parent_id = $result ['parent_id'];
echo "\n<li id='list_$id'><div> ID#$id $name </div>";
if (has_child(query($id))) {
echo "<ol>";
fetch_menu(query($id));
echo "\n</ol>";
}
echo "</li>";
}
}
fetch_menu(query(0)); //call this function with 0 parent id
?>
</ol>
</body>
</html>
No comments:
Post a Comment