zhouer 发表于 2015-11-17 13:48:15

PHP编程之:链接数据库

  写了个类似DBHelepr
  

<?php
class DBHelper{
private $server=&quot;localhost:3306&quot;;//服务器
private $uid=&quot;root&quot;;//MySQL账号
private $pwd=&quot;sa&quot;;//MySQL密码
private $dataBaseName=&quot;db1&quot;;//数据库名称
private $conn;//链接对象
private $charSet=&quot;gb2312&quot;;//字符集类型
private $result;
public function __construct()
{
$this->Connection();
}
public function Free()
{
@ mysql_free_result($this->result);
}
public function __destruct() {
if(!empty($this->result))
{
$this->Free();
}
mysql_close($this->conn);
}
public function Connection()
{
$this->conn=mysql_connect($this->server,$this->uid,$this->pwd) or die('Could not connect: '.mysql_error());
if($this->conn)
{
mysql_query(&quot;SET NAMES $this->charSet&quot;);
mysql_select_db($this->dataBaseName,$this->conn);
}else
{
show_error(&quot;数据库连接错误&quot;,&quot;无法创建数据库连接&quot;);
}
}
/*数据库执行语句,可执行查询添加修改删除等任何sql语句*/
public function Query($sql) {
if ($sql == &quot;&quot;) {
$this->show_error(&quot;SQL语句错误:&quot;, &quot;SQL查询语句为空&quot;);
}
$this->sql = $sql;
$result = mysql_query($sql);
$this->result=$result;
/*if (!$result) {
//调试中使用,sql语句出错时会自动打印出来
if ($this->show_error) {
$this->show_error(&quot;错误SQL语句:&quot;, $sql);
}
} else {
$this->result = $result;
}*/
return $this->result;
}
public function QueryList($sql)
{
if ($sql == &quot;&quot;) {
$this->show_error(&quot;SQL语句错误:&quot;, &quot;SQL查询语句为空&quot;);
}
$resu=mysql_query($sql);
return mysql_fetch_array($resu);
}
public function QueryModel($sql)
{
if ($sql == &quot;&quot;) {
$this->show_error(&quot;SQL语句错误:&quot;, &quot;SQL查询语句为空&quot;);
}
$this->result=mysql_query($sql);
return mysql_fetch_object($this->result);
}
public function show_error($msg=&quot;&quot;,$code=&quot;&quot;)
{
echo &quot;<span class='er'>错误信息:$msg</span><hr>&quot;;
echo &quot;<span class='er'>错误语句:$code</span>&quot;;
}
}
?>


  

版权声明:本文为博主原创文章,未经博主允许不得转载。
页: [1]
查看完整版本: PHP编程之:链接数据库