您的位置:首页 > 数据库

封装数据库类并进行操作

2016-07-20 12:03 281 查看
mysql.class.php

<?php
var $conn;
class mysql{
public function connect($localhost,$name,$password,$database){
$this->conn=mysql_connect($localhost,$name,$password) or die("数据库连接失败!");
mysql_select_db($database) or die("选择数据库失败!");
mysql_query("set names utf8");
}
public function close(){
mysql_close($this->conn);
}
}
?>


AdminDb.class.php

<?php
class adminDb{
public function executeSQL($sql){
$sqlType=strtolower(substr(trim($sql),0,6));
//截取SQL语句前六个字母判断操作类型
$result=mysql_query($sql);
if($sqlType=="select") {
$row=mysql_fetch_array($result);
if(!$row){
return false;
} else {
return $row; //返回结果集
}
}
elseif($sql=="update"||$sql=="delete"||$sql=="insert"){
return $rusult;//返回结果
}
else {
return false;   //既不是select,也不是update,delete,insert,返回错误
}
}
}
?>


/*test.php*/

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<?php
include("mysql.class.php");
include("adminDb.class.php");
$mysql=new mysql();
$mysql->connect("localhost","root","root","test");
$admin=new adminDb();
$sql="select * from user";
$result=$admin->executeSQL($sql);
print_r($result);
              $mysql->close();
?>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: