Modified Preorder Traversal Tree (MPTT) - First Record

Here is our demo table

CREATE TABLE 'tbllinks' (

  'id' int(11) NOT NULL auto_increment,

  'lft' int(11) default NULL,

  'rgt' int(11) default NULL,

  'parent' int(11) default NULL,

  'name' varchar(255) default NULL,

  PRIMARY KEY  ('id')

)

Notice the fields 'lft' and 'rgt'. These are MySQL keywords and useful for our queries.

Here is the PHP code to insert the first record:

<?php

/*//////////CHECK IF ROOT EXISTS-*/

$q = "select rgt from tbllinks where name='ROOT'";

$r = mysql_query($q) or die(mysql_error());

$n = mysql_numrows($r);

if($n == 0)

{

$q = "insert into tbllinks values(NULL,'1','2','0','ROOT')";

mysql_query($q);

$rt = 2;

}

else

{

$row = mysql_fetch_assoc($r);

$rt = $row['rgt'];

}

/*///////////////THE RGT OF THE PARENT BECOMES THE LFT OF THE CHILD NODE*/

/*////////////// THUS WE INCREMENT ALL NODES LFT AND RGT VALUES GREATER THAN PARENT RGT BY 2*/

$nr = $rt 1;

$q = "update tbllinks set lft =lft 2 where lft >= '$rt'";

mysql_query($q);

$q = "update tbllinks set rgt =rgt 2 where rgt >= '$rt'";

mysql_query($q);

/*/////////////INSERT THE RECORD NOW*/

$q = "insert into tbllinks values(NULL,'$rt','$nr','1','###NEW NODE###',)";

mysql_query($q);

?>

 This code will add a ROOT record and then insert the very first record