<?php
//这是一个对MySQL数据库操作的工具类
include 'config.php';
class SqlHelper{
public $host="localhost";
public $username="root";
public $password="root";
public $dbname="lzy123";
public $conn;
//析构函数,连接数据库
public function __construct(){
$this->conn=mysql_connect($this->host,$this->username,$this->password);
if(!$this->conn){
die("连接数据库失败,失败信息".mysql_error());
}
mysql_select_db($this->dbname,$this->conn);
mysql_query("set names utf8");
}
//执行dql语句,返回的是资源,需要释放资源
public function execute_dql($sql){
$res=mysql_query($sql,$this->conn) or die(mysql_error());
return $res;
}
//执行dml语句,返回的是bool值,不需要释放资源
public function execute_dml($sql){
$b=mysql_query($sql,$this->conn) or die(mysql_error());;
if(!$b){
return 0;
}
else{
//检查是否有改动
if(mysql_affected_rows($this->conn)>0){
return 1;//ok
}
else {
return 2;//表示没有行受到影响
}
}
}
//关闭连接的方法
public function close_connect(){
if(!empty($this->conn)){
mysql_close($this->conn);
}
}
}
?>
通过SqlHelper.class.php文件创建对象,就直接可以连接数据库,调用相应的方法可以执行sql语句
<?php
//这是一个对MySQL数据库操作的工具类
include 'config.php';
class SqlHelper{
public $host="localhost";
public $username="root";
public $password="root";
public $dbname="lzy123";
public $conn;
//析构函数,连接数据库
public function __construct(){
$this->conn=mysql_connect($this->host,$this->username,$this->password);
if(!$this->conn){
die("连接数据库失败,失败信息".mysql_error());
}
mysql_select_db($this->dbname,$this->conn);
mysql_query("set names utf8");
}
//执行dql语句,返回的是资源,需要释放资源
public function execute_dql($sql){
$res=mysql_query($sql,$this->conn) or die(mysql_error());
return $res;
}
//执行dml语句,返回的是bool值,不需要释放资源
public function execute_dml($sql){
$b=mysql_query($sql,$this->conn) or die(mysql_error());;
if(!$b){
return 0;
}
else{
//检查是否有改动
if(mysql_affected_rows($this->conn)>0){
return 1;//ok
}
else {
return 2;//表示没有行受到影响
}
}
}
//关闭连接的方法
public function close_connect(){
if(!empty($this->conn)){
mysql_close($this->conn);
}
}
}
?>