<?php
/*
数据库:
增,删,改,查( CURD )操作
C: create
U: update
R: Retrieve
D: delete
*/
class
Mysql {
private
$dbHost;
//主机
private
$dbUser;
//用户名
private
$dbPwd;
//密码
private
$dbName;
//数据库名称
public
function
__construct(
$_dbHost,
$_dbUser,
$_dbPwd,
$_dbName ){
$this->
dbHost =
$_dbHost;
$this->
dbUser =
$_dbUser;
$this->
dbPwd =
$_dbPwd;
$this->
dbName =
$_dbName;
//连接数据库
if(
$this->connect() ){
//成功
//选择数据库, 设定编码
$this->selectDb();
$this->setDbCode();
}
else {
die(
"数据库连接失败" .
mysql_error() );
}
}
public
function
selectDb(){
mysql_select_db(
$this->
dbName );
}
public
function
setDbCode(){
$this->query(
'set names utf8' );
}
public
function
query(
$sql ){
return
mysql_query(
$sql );
}
public
function
connect(){
return
mysql_connect(
$this->
dbHost,
$this->
dbUser,
$this->
dbPwd );
}
//查询所有数据----> 用途: 分页,列表等
public
function
getAll(
$sql ){
$res =
$this->query(
$sql );
$arr =
array();
while(
$row =
mysql_fetch_assoc(
$res ) ){
$arr[] =
$row;
}
return
$arr;
}
//查询某条数据: 用途: 编辑(取出一条数据)等
public
function
getRow(
$sql ){
$res =
$this->query(
$sql );
return
mysql_fetch_assoc(
$res );
}
//统计
public
function
getCol(
$sql ){
$res =
$this->query(
$sql );
$row =
mysql_fetch_row(
$res );
return
$row[
0];
}
//封装插入语句
public
function
add(
$data,
$tbName ){
$sql =
"
INSERT INTO
{
$tbName
} (
";
$sql .=
implode(
',',
array_keys(
$data) ) .
") VALUES (' ";
$sql .=
implode(
"','",
array_values(
$data ) ) .
"')";
return
$this->query(
$sql );
}
//更新
public
function
update(
$data,
$tbName,
$condition ){
$sql =
"
UPDATE
{
$tbName
}
SET
";
foreach(
$data as
$k =>
$v ){
$sql .=
$k .
' = ' .
"'
$v
',";
}
$sql =
substr(
$sql,
0, -
1 );
$sql .=
" " .
$condition;
return
$this->query(
$sql );
}
}
$mysql =
new
Mysql(
"localhost",
"root",
"root",
"php1215_biquge" );
?
>