php封装sql类

<?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" );
? >
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值