pdo mysql 封装_PHP使用PDO封装一个简单易用的DB类

使用

创建测试库和表

create database db_test;

CREATE TABLE `user` (

`id` int(10) unsigned NOT NULL AUTO_INCREMENT,

`name` char(11) NOT NULL,

`created_at` int(10) unsigned NOT NULL,

PRIMARY KEY (`uid`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `user` VALUES ('1', 'wang', '1501109027');

INSERT INTO `user` VALUES ('2', 'meng', '1501109026');

INSERT INTO `user` VALUES ('3', 'liu', '1501009027');

INSERT INTO `user` VALUES ('4', 'yuan', '1500109027');

代码测试

require __DIR__ . '/DB.php';

$db = new DB();

$db->__setup([

'dsn'=>'mysql:dbname=db_test;host=localhost',

'username'=>'root',

'password'=>'******',

'charset'=>'utf8'

]);

$user = $db->fetch('SELECT * FROM user where id = :id', ['id' => 1]);

echo $user['name'];

echo "\n";

$insertId = $db->insert('user', ['name' => 'salamander', 'created_at' => time()]);

echo "insert user {$insertId}\n";

$users = $db->fetchAll('SELECT * FROM user');

foreach ($users as $item) {

echo "user {$item['id']} is {$item['name']} \n";

}

运行结果

c63e2518b7737764f2068b567f71f2d2.png

DB工具类

/**

* User: Salamander

* Date: 2016/9/2

* Time: 9:16

*/

class DB

{

private $dsn;

private $sth;

private $dbh;

private $user;

private $charset;

private $password;

public $lastSQL = '';

public function __setup($config = array())

{

$this->dsn = $config['dsn'];

$this->user = $config['username'];

$this->password = $config['password'];

$this->charset = $config['charset'];

$this->connect();

}

private function connect()

{

if(!$this->dbh){

$options = array(

\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . $this->charset,

);

$this->dbh = new \PDO($this->dsn, $this->user,

$this->password, $options);

}

}

public function beginTransaction()

{

return $this->dbh->beginTransaction();

}

public function inTransaction()

{

return $this->dbh->inTransaction();

}

public function rollBack()

{

return $this->dbh->rollBack();

}

public function commit()

{

return $this->dbh->commit();

}

function watchException($execute_state)

{

if(!$execute_state){

throw new MySQLException("SQL: {$this->lastSQL}\n".$this->sth->errorInfo()[2], intval($this->sth->errorCode()));

}

}

public function fetchAll($sql, $parameters=[])

{

$result = [];

$this->lastSQL = $sql;

$this->sth = $this->dbh->prepare($sql);

$this->watchException($this->sth->execute($parameters));

while($result[] = $this->sth->fetch(\PDO::FETCH_ASSOC)){ }

array_pop($result);

return $result;

}

public function fetchColumnAll($sql, $parameters=[], $position=0)

{

$result = [];

$this->lastSQL = $sql;

$this->sth = $this->dbh->prepare($sql);

$this->watchException($this->sth->execute($parameters));

while($result[] = $this->sth->fetch(\PDO::FETCH_COLUMN, $position)){ }

array_pop($result);

return $result;

}

public function exists($sql, $parameters=[])

{

$this->lastSQL = $sql;

$data = $this->fetch($sql, $parameters);

return !empty($data);

}

public function query($sql, $parameters=[])

{

$this->lastSQL = $sql;

$this->sth = $this->dbh->prepare($sql);

$this->watchException($this->sth->execute($parameters));

return $this->sth->rowCount();

}

public function fetch($sql, $parameters=[], $type=\PDO::FETCH_ASSOC)

{

$this->lastSQL = $sql;

$this->sth = $this->dbh->prepare($sql);

$this->watchException($this->sth->execute($parameters));

return $this->sth->fetch($type);

}

public function fetchColumn($sql, $parameters=[], $position=0)

{

$this->lastSQL = $sql;

$this->sth = $this->dbh->prepare($sql);

$this->watchException($this->sth->execute($parameters));

return $this->sth->fetch(\PDO::FETCH_COLUMN, $position);

}

public function update($table, $parameters=[], $condition=[])

{

$table = $this->format_table_name($table);

$sql = "UPDATE $table SET ";

$fields = [];

$pdo_parameters = [];

foreach ( $parameters as $field=>$value){

$fields[] = '`'.$field.'`=:field_'.$field;

$pdo_parameters['field_'.$field] = $value;

}

$sql .= implode(',', $fields);

$fields = [];

$where = '';

if(is_string($condition)) {

$where = $condition;

} else if(is_array($condition)) {

foreach($condition as $field=>$value){

$parameters[$field] = $value;

$fields[] = '`'.$field.'`=:condition_'.$field;

$pdo_parameters['condition_'.$field] = $value;

}

$where = implode(' AND ', $fields);

}

if(!empty($where)) {

$sql .= ' WHERE '.$where;

}

return $this->query($sql, $pdo_parameters);

}

public function insert($table, $parameters=[])

{

$table = $this->format_table_name($table);

$sql = "INSERT INTO $table";

$fields = [];

$placeholder = [];

foreach ( $parameters as $field=>$value){

$placeholder[] = ':'.$field;

$fields[] = '`'.$field.'`';

}

$sql .= '('.implode(",", $fields).') VALUES ('.implode(",", $placeholder).')';

$this->lastSQL = $sql;

$this->sth = $this->dbh->prepare($sql);

$this->watchException($this->sth->execute($parameters));

$id = $this->dbh->lastInsertId();

if(empty($id)) {

return $this->sth->rowCount();

} else {

return $id;

}

}

public function errorInfo()

{

return $this->sth->errorInfo();

}

protected function format_table_name($table)

{

$parts = explode(".", $table, 2);

if(count($parts) > 1) {

$table = $parts[0].".`{$parts[1]}`";

} else {

$table = "`$table`";

}

return $table;

}

function errorCode()

{

return $this->sth->errorCode();

}

}

class MySQLException extends \Exception { }

Composer安装

框架中使用建议

在框架中使用DB类,用单例模式或者用依赖容器来管理较好。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
自主封装PHP ORM框架,面向对象的PDO数据库操作,API框架,支持Get/Post/Put/Delete多种请求方式。 代码示例: <?php use Models\User; require '../application.php'; require '../loader-api.php'; //适合查询,如:获取用户列表或者单个用户信息 execute_request(HttpRequestMethod::Get, function() { $action = request_action(); //判断是否存在 if ($action == 1) { list($type, $value) = filter_request(array( request_int('type', 1, 2, 3), //1.用户名 2.邮箱 3.手机号 request_string('value'))); $type_field_map = array( 1 => User::$field_username, 2 => User::$field_email, 3 => User::$field_phone ); if ($type == 2 && !is_email($value) || $type == 3 && !is_mobilephone($value)) { die_error(USER_ERROR, $type_field_map[$type]['name'] . '格式无效'); } $user = new User(); $user->set_where_and($type_field_map[$type], SqlOperator::Equals, $value); $result = $user->exists(create_pdo()); echo_result($result ? 1 : 0); //存在返回1,不存在返回0 } //查询单条信息 if ($action == 2) { list($userid) = filter_request(array( request_userid())); //查询单条数据 $user = new User($userid); //set_query_fields可以指定查询字段,下面两种写法均可 //$user->set_query_fields('userid, username, email'); //$user->set_query_fields(array(User::$field_userid, User::$field_username, User::$field_email)); //还可设置where条件进行查询 //$user->set_where_and(User::$field_status, SqlOperator::Equals, 3); //$user->set_where_and(User::$field_truename, SqlOperator::IsNullOrEmpty); //$user->set_where_and(User::$field_age, SqlOperator::In, array(27, 29)); //$user->set_where_and(User::$field_regtime, SqlOperator::LessThan, '-6 month'); //创建数据库连接 $db = create_pdo(); $result = $user->load($db, $user); //也可以用Model的静态方法 //$result = Model::load_model($db, $user, $user); if (!$result[0]) die_error(PDO_ERROR_CODE, '获取用户信息时数据库错误'); if (!$user) di

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值