Multi purpose tree Memory <-> Database library
I've often used some "tree" representation using PHP's multidimentional arrays. This is very usefull, but you get
stopped when you need to save (or load) that tree in a MySQL database. This small script (16 KB) tends to solve that
problem using some references from one record to another.
Imagine you have the following tree to be saved :
$tree = array(
array(
"text" => "Corporate / Investors",
"arbo" => "compinfo",
"childrens" => array(
array(
"text" => "Background / profiles",
"arbo" => "background",
),
array(
"text" => "Shareholders",
"arbo" => "shares",
),
[...]
which for example, will represent the navigation menu you need to use. If you need to save that in your databases, you only need
to call TMDtreeMemToDB($treeID,$tree); and it will be saved to your database.
For each type of tree, you will need 2 tables, one for indexing your trees using names, and one that will store all the trees
informations. Please note that each field you add to the table will be understood by the lib and will be returned as a node
attribute.
Here is the SQL code for creating the tables. Note that "text" and "arbo" are only example of fields that are returned as
your nodes attributes.
#
# Create the tree-index table
#
CREATE TABLE treeindex (
id int(11) NOT NULL auto_increment,
name varchar(32) NOT NULL default '',
root_object_id int(11) NOT NULL default '0',
PRIMARY KEY (id),
FULLTEXT KEY name (name)
) TYPE=MyISAM;
#
# Create the tree table (more than one tree can be stored here,
# but all the indexes can change when saving back to SQL)
#
CREATE TABLE alltreenodes (
id int(11) NOT NULL auto_increment,
ob_head int(11) NOT NULL default '0',
ob_tail int(11) NOT NULL default '0',
ob_next int(11) NOT NULL default '0',
tree_id int(11) NOT NULL default '0',
arbo varchar(32) NOT NULL default '',
text varchar(64) NOT NULL default '',
PRIMARY KEY (id)
) TYPE=MyISAM;
With this example, you can use the following code to retrive your data from MySQL :
mysql_connect( [... some params you should know ...] );
TMDselectTables("treeindex","alltreenodes","childrens");
$tree_id = TMDgetTreeID("thename_of_my_tree");
TDMtreeDBToMem($tree_id);
Finaly, here is the code available for download. This new version (19th of march) correct a bug in the newTree()
function that was destroying some other trees because of a malformed WHERE close. My appologies for that bug.
tree_mem_to_db.php.txt
|