WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDESPHP CLASSESCODE SEARCHARTICLES SEARCHPHP FORUMSPHP MANUALPHP FUNCTIONS LISTWEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search


Submit a code Example / Snippet Join us on FaceBook
Submit a code Example / Snippet Submit Your Code
Poker Tournaments Poker Tournaments
Poker Guide for Developers Poker Guide for Developers
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
פרייסז - השוואת מחירים בסופר
ZeroLag.com
Texas Holdem Poker Evangelists

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : Ajax PHP Tree (Left and Right) with MySQL
Categories : PHP, Databases, MySQL, AJAX, PHP Classes
Suraj Thapaliya
Date : Mar 16th 2007
Grade : 3 of 5 (graded 56 times)
Viewed : 58573
File : 4605.zip
Images : Image 1 , Image 2 , Image 3
Search : More code by Suraj Thapaliya
Action : Grade This Code Example
Tools : My Examples List

Submit your own code examples  Submit your own code examples 
Like this code?
Show the author your appreciation.
 

This example is using AJAX and PHP with a MYSQL database to show the Left and Right Tree. I already use this code on the network business companies where they have a member and the member should have to create his other sub member on his Left or right and other member as well.

Also i have enclose "mysql database connectivity class version 1.3" with new function


Hope you like this example, see attached file above.

tree1.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Tree Structure </title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript" src="scripts1.js"></script>
</head>

<body>
<?php

   
include ("include/host_conf.php");
    include (
"include/mysql.lib.php");
   
$obj=new connect();
    include (
"functions.php");
   
$sn=1; // You can change this value to see the tree related to this member
   
if(empty($sn)) {
       
$sn=1;
    }
   
$sql="SELECT * FROM tbl_tree WHERE id=$sn";
   
main_box($sql);
?>
</body>
</html>



scripts1.js
var xmlHttp
var id
function showHint(str, div){
    if (str.length > 0){
        var url=str
        id = div

//        alert(id)
        xmlHttp=GetXmlHttpObject(stateChanged)
        xmlHttp.open("GET", url , true)
        xmlHttp.send(null)
    stateChanged()
    }
    else{
        document.getElementById(id).innerHTML=""
    }
}

function stateChanged() {
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
        document.getElementById(id).innerHTML=xmlHttp.responseText
    }
}

function GetXmlHttpObject(handler){
    var objXmlHttp=null

    if (navigator.userAgent.indexOf("Opera")>=0){
        alert("This example doesn't work in Opera")
        return
    }
    if (navigator.userAgent.indexOf("MSIE")>=0){
        var strName="Msxml2.XMLHTTP"
        if (navigator.appVersion.indexOf("MSIE 5.5")>=0){
            strName="Microsoft.XMLHTTP"
        }
        try{
            objXmlHttp=new ActiveXObject(strName)
            objXmlHttp.onreadystatechange=handler
            return objXmlHttp
        }
        catch(e){
            alert("Error. Scripting for ActiveX might be disabled")
            return
        }
    }
   
    if (navigator.userAgent.indexOf("Mozilla")>=0){
        objXmlHttp=new XMLHttpRequest()
        objXmlHttp.onload=handler
        objXmlHttp.onerror=handler
        return objXmlHttp
    }
}



functions.php
<?php
/*
    This is the main file of this tree project
    here in this file the DIV is created according to the member ID and it is concanate to the placement_type as well
    for eg if the member id is 1 and the placement type is L then the div id = 1L
   
    This page is called from the Tree1.php for first time
    and it will show the below table with 2 respected links L and R (only if he had a sub member)
   
    and when click on this 2 links they will call javascript function named "showhint" with URL and the ID of the member and DIV ID (1L or 1R)
   
        well this showhint function is in script1.js file it will call the ajaxreturn.php file along with URL and the Div ID
       

       
*/
function main_box($sql=null){
    global
$obj;
   
$obj->query($sql);
    while (
$result = $obj->query_fetch(1)){
       
$id=$result['id'];
       
$name=$result['name'];
       
$pid=$result['parent_id'];
       
$lr=$result['placement_type'];
    }
?>
    <table width="100%" border="0" align="center" cellpadding="1" cellspacing="1" bordercolor="#CCCCCC">
      <tbody>
        <tr>
          <td width="50%" valign="top">&nbsp;</td>
          <td width="100" valign="top">&nbsp;</td>
          <td width="100" valign="top">&nbsp;</td>
          <td width="50%" valign="top">&nbsp;</td>
        </tr>
        <tr>
          <td width="50%">&nbsp;</td>
          <td align="center" colspan="2" style="border:1px solid #ffcc99;" nowrap> &nbsp;
                  <?php echo $name; ?>
          </td>
          <td valign="top" width="50%">&nbsp;</td>
        </tr>
        <tr>
          <td>&nbsp;</td>
          <td valign="top" style="border-bottom:1px solid #ffcc99;">&nbsp;
              <?php
                $sql
="SELECT * FROM tbl_tree WHERE parent_id=$id AND placement_type='L'";
               
$obj->query($sql);
                while (
$result = $obj->query_fetch(1)){
                   
$left=true;
                }
                if (
$left){
                   
$leftCount=$leftCount+1;
                   
$idl=$id."l";
                    echo
"<a href=# onclick=\"showHint('ajaxreturn.php?id=$id&lr=L', '$idl');\"><b>  L  </b> </a> &nbsp;&nbsp;";

                }
                           
           
?>          </td>
          <td valign="top" style="border-left:1px solid #ffcc99;border-bottom:1px solid #ffcc99;"> &nbsp;
              <?php
                $sql
="SELECT * FROM tbl_tree WHERE parent_id=$id AND placement_type='R'";
               
$obj->query($sql);
                while (
$result = $obj->query_fetch(1)){
                   
$right=true;
                }
                if (
$right){
                   
$rightCount=$rightCount+1;
                   
$idr=$id."r";
                    echo
"<a href=# onclick=\"showHint('ajaxreturn.php?id=$id&lr=R', '$idr');\"> <b> R  </b></a> &nbsp;";

                }
                           
           
?>          </td>
          <td width="50%" valign="top">&nbsp;</td>
        </tr>
        <tr>
          <td valign="top" align="middle" colspan="2"><div id="<?php echo $idl; ?>">&nbsp;</div></td>
          <td valign="top" align="middle" colspan="2"><div id="<?php echo $idr; ?>">&nbsp;</div></td>

        </tr>
      </tbody>
</table>
<?php
} // function Close
?>   



db_tree.txt
-- phpMyAdmin SQL Dump
-- version 2.6.0-pl3
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Mar 16, 2007 at 08:15 PM
-- Server version: 4.1.8
-- PHP Version: 5.0.3
--
-- Database: `db_tree`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_tree`
--

CREATE TABLE tbl_tree (
  id int(11) NOT NULL auto_increment,
  name varchar(50) NOT NULL default '',
  parent_id int(11) NOT NULL default '0',
  placement_type char(1) NOT NULL default '',
  PRIMARY KEY  (id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_tree`
--

INSERT INTO tbl_tree (id, name, parent_id, placement_type) VALUES (1, 'Suraj Thapaliya', 0, '');
INSERT INTO tbl_tree (id, name, parent_id, placement_type) VALUES (2, 'Janaki Thapaliya', 1, 'L');
INSERT INTO tbl_tree (id, name, parent_id, placement_type) VALUES (3, 'Sujan Thapaliya', 1, 'R');
INSERT INTO tbl_tree (id, name, parent_id, placement_type) VALUES (4, 'Kamal Thapa', 2, 'L');



ajaxreturn.php
<?php
   
include ("include/host_conf.php");
    include (
"include/mysql.lib.php");
   
$obj=new connect();
    include(
"functions.php");
   
$sql="SELECT * FROM tbl_tree WHERE parent_id=".$_GET['id']." AND placement_type='".$_GET['lr']."'";
   
main_box($sql);
?>



mysql.lib.php
<?php
/*******************
Mr. Suraj Thapaliya
PHP Programmer
http://www.surajthapaliya.com.np
version 1.3
*/
class connect
{
    var
$Host = C_DB_HOST;            // Hostname of our MySQL server
   
var $Database = C_DB_NAME;        // Logical database name on that server
   
var $User = C_DB_USER;            // Database user
   
var $Password = C_DB_PASS;        // Database user's password
   
var $Link_ID = 0;                // Result of mysql_connect()
   
var $Query_ID = 0;                // Result of most recent mysql_query()
   
var $Record    = array();            // Current mysql_fetch_array()-result
   
var $Row;                        // Current row number
   
var $Errno = 0;                    // Error state of query
   
var $Error = "";

    function
halt($msg)
    {
        echo(
"</TD></TR></TABLE><B>Database error:</B> $msg<BR>\n");
        echo(
"<B>MySQL error</B>: $this->Errno ($this->Error)<BR>\n");
        echo
"Session halted.";
        return
$this->Error;
    }

    function
connect()
    {
        if(
$this->Link_ID == 0)
        {
           
$this->Link_ID = mysql_connect($this->Host, $this->User, $this->Password);
            if (!
$this->Link_ID)
            {
               
$this->halt("Link_ID == false, connect failed");
            }
           
$SelectResult = mysql_select_db($this->Database, $this->Link_ID);
            if(!
$SelectResult)
            {
               
$this->Errno = mysql_errno($this->Link_ID);
               
$this->Error = mysql_error($this->Link_ID);
               
$this->halt("cannot select database <I>".$this->Database."</I>");
            }
        }
    }

    function
query($Query_String)
    {
       
$this->connect();
       
$this->Query_ID = mysql_query($Query_String,$this->Link_ID);
       
$this->Row = 0;
       
$this->Errno = mysql_errno();
       
$this->Error = mysql_error();
        if (!
$this->Query_ID)
        {
           
$this->halt("Invalid SQL: ".$Query_String);
        }
        return
$this->Query_ID;
    }
   
function
query_fetch($fetch=0)
{
    if(
$fetch==0) {
       
$result=@mysql_fetch_assoc($this->Query_ID);
    } else {
       
$result=@mysql_fetch_array($this->Query_ID);
    }
   
    if(!
is_array($result))
    return
false;
   
$this->total_field=mysql_num_fields($this->Query_ID);

    foreach(
$result as $key=>$val){
       
$result[$key]=trim(htmlspecialchars($val));
    }
     return
$result;
}

function
query_fetch_tr($css='',$col_name='no',$update='no',$delete='no',$add='no',$not_show='no',$total_rows=0)
{
    if(!empty(
$not_show)) {
       
$val=0;
     } else {
       
$val=1;
     }
   
// For Add

       
if($add=="yes") {
            if(!empty(
$update))  $c=$c+1;
            if(!empty(
$delete)) $c=$c+1;
           
$colspan=$this->num_field()+$c;
           
$tr_output="<tr><td colspan='$colspan'><a href='?mode=add'> Add New Data</a> </tr> ";
        }
   
   
// End of Add
   
if($col_name=="yes") {
       
$tr_output.="<tr>";
        for(
$j=$val;$j<$this->num_field();$j++) {
           
$tr_output.="<th>".ucwords(strtolower($this->get_field_name($j)));
        }
       
// For Update
       
if($update=="yes") {
           
$addNewTD="<th>Update</th>";
        } else {
           
$addNewTD="";
        }
       
// End of Update
        // For Delete
       
if($delete=="yes") {
           
$addDelTD="<th>Delete</th>";
        } else {
           
$addDelTD="";
        }
       
       
// End of Delete
       
$tr_output.="$addNewTD $addDelTD </tr>";
    }
    if(
$total_rows==0) {
        echo 
$tr_output;
    }
   
    while(
$result=$this->query_fetch(1))
    {
       
        if(
is_array($result))
        {
            if(
$css!="")
            {
               
$css_val="class=".$css;
            }
           
$tr_output.="<tr $css_val>";
           
            for(
$i=$val;$i<$this->num_field();$i++)
            {
                if(
$result[$i]=="")
                {
                   
$result[$i]="&nbsp;";
                }
               
$tr_output.="<td>".$result[$i]."</td>";
            }
            if(
$update=="yes") {
               
$tr_output.="<td><a href='?sn=$result[0]&mode=update'>Update</a></td>";
            }
            if(
$delete=="yes") {
               
$tr_output.="<td><a href='?sn=$result[0]&mode=delete'> Delete</a> </td>";
            }
           
$tr_output.="</tr>";
        }
            echo
$tr_output;
            unset(
$tr_output);
    }
}


function
paging($sqlPaging="",$offSet=0) {
   
$sqlPaging=$sqlPaging;
   
$eu = ($start - 0);
   
$limit = $offSet;                             
   
$a = $eu + $limit;
   
$back = $eu - $limit;
   
$next = $eu + $limit;
   
$mainQuery=$sqlPaging." limit $eu,$limit";
   
$this->query($mainQuery);
   
$nume=$this->num_rows();
echo
"<table align = 'right' width='500' border=0>
<tr>
<td  align='right' width='50%'>"
;
if(
$back >=0) {
print
"<a href='$page_name?start=$back'><font face='arial' size='1'> << </font></a>";
}
echo
" Page ";
$i=0;
$l=1;
for(
$i=0;$i < $nume;$i=$i+$limit){
    if(
$i <> $eu){
        echo
" <a href='$page_name?start=$i'><font face='arial' size='1'>$l</font></a> ";
    } else {
        echo
"<font face='arial' size='1' color=red> &nbsp;$l</font>";
    }     
   
$l=$l+1;
    echo
"&nbsp;";
}
    if(
$a < $nume) {
        print
"<a href='$page_name?start=$next'><font face='arial' size='1'> >> </font></a>";
    }
    echo
"</tr></table>";

   
}

function
num_field()
{
    return
mysql_num_fields($this->Query_ID);
}
function
get_field_name($i)
{
    return
mysql_field_name($this->Query_ID,$i);
}


/*
function fetch_field()
{
    return mysql_fetch_field($this->Query_ID,2);
}
*/

function next_record()
    {
       
$this->Record = mysql_fetch_array($this->Query_ID);
       
$this->Row += 1;
       
$this->Errno = mysql_errno();
       
$this->Error = mysql_error();
       
$stat = is_array($this->Record);
        if (!
$stat)
        {
           
mysql_free_result($this->Query_ID);
           
$this->Query_ID = 0;
        }
        return
$this->Record;
    }

    function
num_rows()
    {
        return
mysql_num_rows($this->Query_ID);
    }
    function
maxRow($tablename,$field,$condition)
    {
       
$sql="select max($field) from $tablename $condition";
       
$this->query($sql);
       
$result=@mysql_fetch_array($this->Query_ID);
        return
$result[0];
    }
    function
affected_rows()
    {
        return
mysql_affected_rows($this->Link_ID);
    }

    function
optimize($tbl_name)
    {
       
$this->connect();
       
$this->Query_ID = @mysql_query("OPTIMIZE TABLE $tbl_name",$this->Link_ID);
    }

    function
clean_results()
    {
        if(
$this->Query_ID != 0) mysql_free_result($this->Query_ID);
    }

    function
close()
    {
        if(
$this->Link_ID != 0) mysql_close($this->Link_ID);
    }
}
?>



host_conf.php
<?php
    $host
="host name";
       
$user_name="user name";
       
$password="password";
   
$db="db_tree";


       
define("C_DB_HOST",$host);
       
define("C_DB_USER",$user_name);
       
define("C_DB_PASS",$password);
       
define("C_DB_NAME",$db);
?>



Specify your connection settings and create a link to a MySQL database.
Categories : PHP, PHP Classes, Databases, MySQL, Beginner Guides
[PHP5] aDB PDO LIKE Database Abstraction. Switch easily from one db server to another, strong errors management, manage transactions, queries preparation and more.
Categories : PHP, PHP Classes, Databases, MS SQL Server, MySQL
bookmarker - PHP, PHPLIB, MySQL WWW based bookmark manager
Categories : MySQL, PHP, MySQL, Complete Programs, Databases
MySQL Handler
Categories : PHP, Databases, MySQL, Classes and Objects, PHP Classes
Simple Mini Poll class library (SimPoll)
Categories : PHP, PHP Classes, Databases, MySQL, Complete Programs
This program allows you to upload an ODBC ressource - i.e. an MS-Access database to a MySQL server.
Categories : Databases, MySQL, Complete Programs, PHP, Databases
Simple usersOnline class - keep track of how many users are online on your site
Categories : PHP, PHP Classes, Databases, MySQL
PostGreSQL and MySQL 2 in 1 db Manager
Categories : PHP, PHP Classes, Databases, PostgreSQL, MySQL
YellowPages Content Grabber (PHP5 +)
Categories : PHP, PHP Classes, Regexps, Databases, MySQL
Password reminder
Categories : PHP, PHP Classes, Databases, MySQL, Mail
Online Automatic Class Generator for MySQL Tables
Categories : PHP, PHP Classes, Classes and Objects, Databases, MySQL
Data Retrieve from Mysql using AJAX with PHP
Categories : PHP, AJAX, Date Time, Databases, MySQL
phpFormGenerator for Dynamic Form Generation from MySQL
Categories : PHP, PHP Classes, MySQL, Databases, HTML and PHP
PHP Object Example of the Perl DBI with MySQL
Categories : PHP, PHP Classes, MySQL, Databases, Perl
PHP Transfer data from text file to Mysql Table
Categories : PHP, PHP Classes, Filesystem, Databases, MySQL
 Ken Than wrote :1890
how to contact you for script development? Contact me via gmail -> [email protected] or yahoo messenger -> [email protected]