PDA

View Full Version : tree menu view with PHP and MySQL



xmatt1
27 Jul 2007, 12:14 PM
Hello everyone!

Well, i was looking for a great example about tree menu view with PHP and MySQL and i didnt found a GREAT EXAMPLE so i did it in my self and im here for show u as it is easy :D
so lets start it. This Example its to build a tree menu that check the users permissions and our profiles so the our database look like this



CREATE TABLE profile (
idProfile INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
PRIMARY KEY(idProfile)
)
TYPE=InnoDB;

CREATE TABLE page (
idPage INT(11) NOT NULL AUTO_INCREMENT,
parent_id INT(11) NULL,
name VARCHAR(50) NULL,
url VARCHAR(80) NULL,
action VARCHAR(20) NULL,
visible TINYINT(3) UNSIGNED NULL,
order INT(11) NULL,
PRIMARY KEY(idPage)
)
TYPE=InnoDB;

CREATE TABLE user (
idUser INT(11) NOT NULL AUTO_INCREMENT,
idProfile INT(11) NOT NULL,
name VARCHAR(50) NOT NULL,
login VARCHAR(12) NOT NULL,
password VARCHAR(12) NOT NULL,
accessDate DATETIME NULL,
lastAccess DATETIME NULL,
visits INT(11) NULL,
PRIMARY KEY(idUser),
INDEX user_FKIndex1(idProfile),
FOREIGN KEY(idProfile)
REFERENCES profile(idProfile)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
TYPE=InnoDB;

CREATE TABLE permission (
idPage INT(11) NOT NULL,
idProfile INT(11) NOT NULL,
INDEX permission_FKIndex2(idProfile),
INDEX permission_FKIndex1(idPage),
FOREIGN KEY(idProfile)
REFERENCES profile(idProfile)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
FOREIGN KEY(idPage)
REFERENCES page(idPage)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
TYPE=InnoDB;


Great so u have our databese structure and now you have to insert some records.
i'll explain our database structure so
1. We have a profile table that we insert the users profile if is Admin or its only a simple user
2. We have a page table that we insert the idProfile that check what profile can access this page and etc..
3. We have a user table that we insert a user with ur profile in profile table.
4. and then we have a permission table that define what profile acces page if the user can acces or not! cool ;)

so now lets to the visual part. First create a html file like this:
index.html:


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>EXT - Tree View with PHP and MySQL </title>

<link rel="stylesheet" type="text/css" href="../includes/ext/resources/css/ext-all.css" />

<script type="text/javascript" src="../includes/ext/adapter/ext/ext-base.js"></script> <!-- ENDLIBS -->
<script type="text/javascript" src="../includes/ext/ext-all.js"></script>

<script type="text/javascript" src="menu.js"></script>

<style type="text/css">
#tree {
float:left;
margin:20px;
border:1px solid #c3daf9;
width:250px;
height:300px;
overflow:auto;
}
.folder .x-tree-node-icon{
background:transparent url(../includes/ext/resources/images/default/tree/folder.gif);
}
.x-tree-node-expanded .x-tree-node-icon{
background:transparent url(../includes/ext/resources/images/default/tree/folder-open.gif);
}
</style>
</head>
<body>

<div id="tree"></div>

</body>
</html>



and now the 2nd step javascript code:
menu.js:


var TreeTest = function(){
// shorthand
var Tree = Ext.tree;

return {
init : function(){
// yui-ext tree
var tree = new Tree.TreePanel('tree', {
animate:true,
loader: new Tree.TreeLoader({dataUrl:'get-nodes.php'}),
containerScroll: true,
});

// add a tree sorter in folder mode

// set the root node
var root = new Tree.AsyncTreeNode({
text: 'Menu',
draggable:false, // disable root node dragging
id:'source'
});

tree.setRootNode(root);

tree.render();

root.expand(false,false);
}
};
}();

Ext.EventManager.onDocumentReady(TreeTest.init, TreeTest, true);


and now our user class php - ps: i have a extend DB class in my configure.inc.php but its easy for u understand that :D
users.inc.php:



class users {

var $db;

function users()
{
$this->db = $GLOBALS['db'];
}

function getParent()
{
$sql = "SELECT * FROM page WHERE parent_id = 0 ";

$query = $this->db->query($sql);

while($obj = $this->db->fetch_object($query)) {

$children = $this->getChild($obj->idPage);

if($children){

$tmp['text'] = $obj->name;
$tmp['id'] = $obj->idPage;
$tmp['leaf'] = false;
$tmp['cls'] = 'folder';
$tmp['children'] = $children;

$nodes[] = $tmp;
}
}

print json_encode($nodes);
}

function getChild($id)
{
# look in sql INNER JOIN user as usu ON usu.idUser = '1' you have to alter it for user logon in the site u can do it by $_SESSION['idUser'] but other way i put 1 for a test
$sql = " SELECT pag.*

FROM page as pag

INNER JOIN user as usu ON usu.idUser = '1'
INNER JOIN permission as per ON (per.idPage = pag.idPage AND per.idProfile = usu.idProfile)

WHERE pag.parent_id = '".$id."' AND pag.visible = '1'
ORDER BY pag.order, pag.name ";

$query = $this->db->query($sql);

while($obj = $this->db->fetch_object($query)){

$tmp['text'] = $obj->name;
$tmp['id'] = $obj->idPage;
$tmp['leaf'] = true;
$tmp['cls'] = 'file';

$nodes[] = $tmp;
}

return $nodes;
}
}


and now our json enode in
get-nodes.php


<?
require_once '../includes/configure.inc.php';
require_once CLASSES.'users.inc.php';

$users = new users;

$users->getParent();
?>

akbeyfb
31 Jul 2007, 7:20 AM
hi you have to give configure.inc.php file and also we have to assign query() and fetch_object() functions to work it...can you give?

xmatt1
31 Jul 2007, 7:52 AM
HI.. sure i can give u...
this is the configure.inc.php


<?

define(PREFIXO, "fv_"); # prefix from table
define(PROJETO, "forever"); # database
define(_WEBMASTER_, "sistemas@mattsoft.eti.br"); # your email

$arhost[0] = "localhost";
$ardb[0] = "forever";
$aruser[0] = "root";
$arpass[0] = "root";

define(PATH, "E:/Projetos/WEB/PHP/forever/");
define(URL, "http://localhost/PHP/forever/");

error_reporting (E_ALL ^ E_NOTICE);

define(INCLUDES, PATH .'includes/'); # includes dir
define(CLASSES, INCLUDES .'class/'); # classes dir
define(PAGESADMIN, PATH.'url/'); # admin dir
define(EXTRASADMIN, PATH.'extras/'); # extra admin dir

# here are the main classes
require_once(INCLUDES .'funcoes.inc.php'); # generic functions
require_once(INCLUDES .'db.inc.php'); # database functions
require_once(INCLUDES .'sendMail.inc.php'); # send email

# Start the database connection
$db = new db();
$db->connect();
$noheader = 1;

# no cache in the files
if ( !$noheader ) {
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last Modified: '. gmdate('D, d M Y H:i:s') .' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
header('Pragma: no-cache');
header('Expires: 0');
}
?>


this the db.inc.php
[php]
<?

define('VM_FETCH_ARRAY' ,'array');
define('VM_FETCH_ASSOC' ,'assoc');
define('VM_FETCH_OBJECT','object');
define('VM_FETCH_ROW' ,'row');

class db
{
var $link; #ponteiro de conexao com o servidor
var $host; #endere

Johann
7 Aug 2007, 11:48 AM
Hello!

I'm new here. Sorry for my bad english, I'm from Germany.

I have many Problems with your Script. Is there any way to get this complete Project in one ZIP-File?

I can't find my error. My IE shows an error in line 13 / 13, but I can't find anyting...

Thanks a lot.

Grimsk
9 Aug 2007, 1:41 PM
first get FF and FireBug !

JorisA
10 Aug 2007, 2:36 AM
Hi great example. I'm thinking about using the this (http://www.sitepoint.com/article/hierarchical-data-database/1) for storing my tree in the database. Looks a bit complicated but if you put all the logic in the users class it should be easy to use.

tschenck
8 Apr 2008, 4:52 AM
Hi great example. I'm thinking about using the this (http://www.sitepoint.com/article/hierarchical-data-database/1) for storing my tree in the database. Looks a bit complicated but if you put all the logic in the users class it should be easy to use.
If you are using PHP, this class is already neatly implemented in http://pear.php.net/package/Tree - we run it with big trees on high volume sites and it's sweet.

regards,

Toby

ted
30 Jun 2008, 10:46 PM
here are the main classes

require_once(INCLUDES .'funcoes.inc.php'); # generic functions

require_once(INCLUDES .'db.inc.php'); # database functions

require_once(INCLUDES .'sendMail.inc.php'); # send email


Greate example, however, I couldn't found the 'funcoes.inc.php' and 'sendMail.inc.php' in the thread.

anandafit
11 Nov 2008, 1:34 AM
Hi,

I tried the example that described in above. But it did not working properly. I can't understand my fault.

deardeer76
4 Feb 2009, 6:57 PM
Hi, could you give us some data in the database tables? With Insert SQL command. Thanks!

extjs_new
24 Feb 2009, 10:59 AM
Hi there, is there any complete zip for this? with all the javascript, html, php, SQL text for creating the database and inserting sample data?

Also, I noticed that it is only 1 downlevel tree menu, isn't it? (I mean, a menu's with only 1 sub-menus)

As I can see, the database structure is nice. But how can I retreive (recursively) children beyond the 1st level (going deeper thru tree menu) .

Thanks a lot