给一个朋友写的,复制一个树的分枝
表
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);
}
}