php 链接数据库,以及一些常用的处理
<?php
class conn
{
private $host;
private $root;
private $pass;
function __construct($host,$root,$pass)
{
$this->host = $host;
$this->root = $root;
$this->pass = $pass;
$this->connect();
}
function connect()
{
$id = mysql_connect($this->host,$this->root,$this->pass) or die("Can not connect MySql !");
mysql_query("set names utf8");
}
function create_new_tb($tbname,$column)
{
mysql_query("CREATE TABLE ".$tbname."(`tag` char(2) default '1')")or die("New table create failed".mysql_error());
$number = 0;
$column = explode("/t",$column);
print_r($column);
while($number<count($column))
{
mysql_query("alter table ".$tbname." add ".$column[$number]." varchar(255) ") or die("<br>create field failed!<br>");
$number++;
}
//$this->column = implode(",",$this->column);
//$this->column = "tag,".$this->column;
//$this->column = explode(",",$this->column);
}
function fetch_dbname()
{
$db = mysql_query("show databases");
$i =0;
while($row= mysql_fetch_array($db))
{
$dbname[$i] = $row[0];
$i++;
}
return $dbname;
}
function fetch_tbname($db)
{
if(isset($db))
{
mysql_query("use ".$db."");
$tb = mysql_query("show tables");
if(empty($tb))
{
return;
}
$i =0;
while($row= mysql_fetch_array($tb))
{
$tbname[$i] = $row[0];
$i++;
}
return $tbname;
}
else
{
echo "No database name was delivered!";
}
}
function insert_field($dbname,$tbname,$arr,$value)
{
$use = "use ".$dbname."";
$query = "insert into $tbname(";
$query.= implode(",",$arr);
$query.= ") values('";
$query.= implode("','",$value);
$query.= "')";
mysql_query($use) or die(mysql_error());
mysql_query($query)or die(mysql_error());
}
function read_data($dbname,$tbname)
{
$r_use = "use ".$dbname."";
$sel = "select c_tbname,e_tbname from ".$tbname." ";
mysql_query($r_use) or die(mysql_error());
$result = mysql_query($sel) or die(mysql_error());
$i = 0;
while($row = mysql_fetch_row($result))
{
$value[$i] = $row;
$i++;
}
return $value;
}
function fetch_field($tbname)
{
if(!empty($tbname))
{
$sql = "select * from ".$tbname."";
$res = mysql_query($sql)or die(mysql_error());
$i = 0;
while($row= mysql_fetch_field($res))
{
$fdname[$i] = $row->name;
$i++;
}
return $fdname;
}
else
return ;
}
function fetch_Vname($db)
{
if(!empty($db))
{
mysql_query("use ".$db."");
$tb = mysql_query("show table status where comment = 'view'");
$i =0;
while($row= mysql_fetch_array($tb))
{
$tbname[$i] = $row[0];
$i++;
}
return $tbname;
}
else
return;
}
function fetch_content($dbname,$tbname)
{
if(!empty($dbname))
{
mysql_query("use ".$dbname."");
$content = "select * from ".$tbname."";
$tb = mysql_query($content);
$i =0;
while($row= mysql_fetch_array($tb))
{
$tmp[$i] = $row;
$i++;
}
return $tmp;
}
else
return;
}
}
?>