以下是对PHP连接数据进行的简单封装代码,能够实现对数据库的增删改查
/**
* mysql connection configure
* 2016-04-10
* Ron
*/
class DBUtils{
private $ychat_host = "localhost";
private $ychat_username = "root";
private $ychat_password = "12345";
private $ychat_database = "talk";
private $conn;
/*
function __construct($dbhost,$dbusername,$password,$database){
$this->ychat_host=$dbhost;
$this->ychat_username=$dbusername;
$this->ychat_password=$password;
$this->ychat_database=$database;
$this->connect();
}*/
function __construct(){
$this->connect();
}
function connect(){
$this->conn = mysql_connect($this->ychat_host,$this->ychat_username,$this->ychat_password)
or die ("connection MySQL failed!");
mysql_select_db($this->ychat_database,$this->conn);
mysql_query("set names utf8");
}
function dbClose(){
mysql_close($this->conn);
}
//对mysql_query()、mysql_fetch_array()、mysql_num_rows()函数进行封装
function query($sql){
return mysql_query($sql);
}
function myArray($result){
return mysql_fetch_array($result);
}
function rows($result){
return mysql_num_rows($result);
}
//自定义查询数据方法
function select($table,$condition){
return $this->query("SELECT * FROM $table $condition");
}
function insert($table,$fields,$value){
$this->query("INSERT INTO $table $fields VALUES $value");
}
function update($table,$change,$condition){
$this->query("UPDATE $table SET $change $condition");
}
function delete($table,$condition){
$this->query("DELETE FROM $table $condition");
}
}
?>
用test.php来进行测试
header("Content-type:text/html;charset=utf-8");
// include('../controller/connect.php');
require("../controller/connect.php");
$db = new DBUtils();
/*
$delete = $db->delete("userinfo", "where id = 8");
echo "delete:".$delete;
$db->dbClose();*/
// $db->insert("userinfo", "(username,password)", "('Kim nana','123456')");
$select = $db->select("userinfo", "");
$row = $db->rows($select);
echo $row;
?>
id | username | sex |
---|
while ($array = $db->myArray($select)) {
echo "
";echo "
".$array['id']."";echo "
".$array['username']."";echo "
".$array['sex']."";echo "
";}
?>