复制树的分枝

给一个朋友写的,复制一个树的分枝

 

CREATE TABLE IF NOT EXISTS `tree` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `pid` int(11) NOT NULL,
  `name` varchar(20) CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;


INSERT INTO `tree` (`id`, `pid`, `name`) VALUES
(1, 0, '山东'),
(2, 1, '济南'),
(3, 1, '济宁'),
(4, 1, '潍坊'),
(5, 2, '济南市市中区');

现在要复制山东这个树枝,dome.php

<?php
header("Content-type: text/html; charset=utf-8");       


class cloneTree{

	protected $top;

	public function __construct($id){
		$this->top = dbmysql::find("select * from tree where id=".$id);
		print_r($this->top);
	}

	public function getTopid(){
		$pid = $this->top["pid"];
		$name = $this->top["name"]."_重命名";
		return dbmysql::Insert("insert into tree(pid,name)values($pid,'$name')");
	}

	public function run(){
		$newid = $this->getTopid();
		$pid = $this->top["id"];
		print_r($newid);
		$this->tree($pid,$newid);
	}

	public function tree($pid,$newid){
		$arr = dbmysql::query("select * from tree where pid=".$pid);
		foreach ($arr as $k => $v) {
			$name = $v["name"]."_重命名";
			$newid2 = dbmysql::Insert("insert into tree(pid,name)values($newid,'$name')");
			$pid2 = $v["id"];
			$this->tree($pid2,$newid2);
		}
	}

}

// 复制山东这个树枝,山东的id是1
$ct = new cloneTree(1);
$ct->run();



class dbmysql{
	private static $host = "localhost";
	private static $username = "root";
	private static $password = "";
	private static $dbname = "test";
	private static $con;

	static function conn(){
		if(!self::$con){
			self::$con = mysql_connect(self::$host,self::$username,self::$password);
			mysql_select_db(self::$dbname);
			mysql_set_charset("utf8");
		}
		return self::$con;
	}

	static function Insert($sql){
		$result = mysql_query($sql,self::conn());
		if(!$result){
			die(mysql_error());
		}
		return mysql_insert_id();
	}

	static function query($sql){
		$result = mysql_query($sql,self::conn());
		if(!$result){
			die(mysql_error());
		}
		$rows = array();
		while($row = mysql_fetch_assoc($result)){
			$rows[] = $row;
		}
		return $rows;
	}

	static function find($sql){
		$result = mysql_query($sql,self::conn());
		if(!$result){
			die(mysql_error());
		}
		return mysql_fetch_assoc($result);
	}

}

 

转载于:https://my.oschina.net/tongjh/blog/729736

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值