php连接mysql数据库 pdo_php pdo方式连接mysql数据库

本文介绍了如何使用PDO连接数据库,并提供了一个详细的PDO操作封装类示例,该类包含了预处理、绑定参数、执行查询、插入、更新、删除等常见数据库操作。通过这个类,可以更方便地在PHP项目中进行数据库交互。
摘要由CSDN通过智能技术生成

PDO方法连接数据库是一种比较流行的方法:它的操作比较简单

如果只是简单的使用的话:

// 数据库连接

try {

$this->pdo = new \PDO("mysql:host=" . $hostname . ";port=" . $port . ";dbname=" . $database, $username, $password, array(\PDO::ATTR_PERSISTENT => true));

} catch(\PDOException $e) {

trigger_error('Error: Could not make a database link ( ' . $e->getMessage() . '). Error Code : ' . $e->getCode() . '
');

}

// 调用方法很简单

$query=$pdo->query('SELECT id,name FROM user');

$row=$query->fetch();

但我们更多的使用是用于实际的项目中,有必要把pdo的操作方式封装成一个类

class mPDO

{

public $SqlBug = ''; // 记录mysql调试语句,可以查看完整的执行的mysql语句

private $pdo = null; // pdo连接

private $statement = null;

public function __construct($hostname, $username, $password, $database, $charset, $port = "3306")

{

try {

$this->pdo = new \PDO("mysql:host=" . $hostname . ";port=" . $port . ";dbname=" . $database, $username, $password, array(\PDO::ATTR_PERSISTENT => true));

} catch(\PDOException $e) {

trigger_error('Error: Could not make a database link ( ' . $e->getMessage() . '). Error Code : ' . $e->getCode() . '
');

}

$this->pdo->exec("SET NAMES '" . $charset . "'");

$this->pdo->exec("SET CHARACTER SET " . $charset);

$this->pdo->exec("SET CHARACTER_SET_CONNECTION=" . $charset);

$this->pdo->exec("SET SQL_MODE = ''");

}

public function prepare($sql)

{

$this->statement = $this->pdo->prepare($sql);

$this -> SqlBug .= "\n". '' . "\n";

}

public function bindParam($parameter, $variable, $data_type = PDO::PARAM_STR, $length = 0)

{

if ($length) {

$this->statement->bindParam($parameter, $variable, $data_type, $length);

} else {

$this->statement->bindParam($parameter, $variable, $data_type);

}

}

public function execute()

{

try {

if ($this->statement && $this->statement->execute()) {

$data = array();

while ($row = $this->statement->fetch(PDO::FETCH_ASSOC)) {

$data[] = $row;

}

$result = new stdClass();

$result->row = (isset($data[0])) ? $data[0] : array();

$result->rows = $data;

$result->num_rows = $this->statement->rowCount();

}

} catch(PDOException $e) {

trigger_error('Error: ' . $e->getMessage() . ' Error Code : ' . $e->getCode());

}

}

public function query($sql, $params = array())

{

$this->statement = $this->pdo->prepare($sql);

$result = false;

$this -> SqlBug .= "\n". '' . "\n";

try {

if ($this->statement && $this->statement->execute($params)) {

$data = array();

while ($row = $this->statement->fetch(\PDO::FETCH_ASSOC)) {

$data[] = $row;

}

$result = new \stdClass();

$result->row = (isset($data[0]) ? $data[0] : array());

$result->rows = $data;

$result->num_rows = $this->statement->rowCount();

}

} catch (PDOException $e) {

trigger_error('Error: ' . $e->getMessage() . ' Error Code : ' . $e->getCode() . '
' . $sql);

exit();

}

if ($result) {

return $result;

} else {

$result = new stdClass();

$result->row = array();

$result->rows = array();

$result->num_rows = 0;

return $result;

}

}

public function executeUpdate($sql)

{

return $this->pdo->exec($sql);

}

/**

* 获得所有查询条件的值

*/

public function fetchAll($sql, $params = array())

{

$rows = $this->query($sql, $params)->rows;

return !empty($rows) ? $rows : false;

}

/**

* 获得单行记录的值

*/

public function fetchAssoc($sql, $params = array())

{

$row = $this->query($sql, $params)->row;

return !empty($row) ? $row : false;

}

/**

* 获得单个字段的值

*/

public function fetchColumn($sql, $params = array())

{

$data = $this->query($sql, $params)->row;

if(is_array($data)) {

foreach ($data as $value) {

return $value;

}

}

return false;

}

/**

* 返回statement记录集的行数

*/

public function rowCount($sql, $params = array())

{

return $this->query($sql, $params)->num_rows;

}

/**

* 插入数据

* @param string $table 表名

* @param Array $data 数据

* @return int InsertId 新增ID

*/

public function _insert($table, $data)

{

if (!is_array($data) || count($data) == 0) {

return 0;

}

$field_arr = array();

foreach ($data as $key=>$val) {

$field_arr[] = " `$key` = '$val' ";

}

$sql = "INSERT INTO " . $table . " SET " . implode(',', $field_arr);

$this -> query($sql);

return $this->getLastId();

}

/**

* 更新数据

* @param string $table 表名

* @param Array $data 数据

* @param string $where 更新条件

* @return int 影响数

*/

public function _update($table, $data, $where = '')

{

// $this -> Affected = 0;

if(empty($where)) {

return 0;

}

if (!is_array($data) || count($data) == 0) {

return 0;

}

$field_arr = array();

foreach ($data as $key=>$val)

$field_arr[] = " `$key` = '$val' ";

$sql = "UPDATE " . $table . " SET " . implode(',', $field_arr) . " WHERE " . $where;

return $this->pdo->exec($sql);

}

/**

* 获得影响集合中

*/

public function _delete($table, $where = "")

{

if(empty($where)) {

return 0;

}

$sql = "DELETE FROM " . $table . " WHERE " . $where;

return $this->pdo->exec($sql);

}

/**

* 获得影响集合中

*/

public function countAffected()

{

if ($this->statement) {

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

} else {

return 0;

}

}

/*

* 获得插入id

*/

public function getLastId()

{

return $this->pdo->lastInsertId();

}

public function escape($value) {

$search = array("\\", "\0", "\n", "\r", "\x1a", "'", '"');

$replace = array("\\\\", "\\0", "\\n", "\\r", "\Z", "\'", '\"');

return str_replace($search, $replace, $value);

}

/**

* 返回错误信息也包括错误号

*/

public function errorInfo()

{

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

}

/**

* 返回错误号

*/

public function errorCode()

{

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

}

public function __destruct()

{

$this->pdo = null;

}

}

// 当然还有mysql_connect,mysqli的方法都可以连接数据库了

转载时请注明出处及相应链接,本文永久地址:https://blog.yayuanzi.com/3099.html

75d087ef9a9fb11dc373caaf33adbf7f.png

54fe503922528d762f0cfb4f3f25f0cf.png

微信打赏

ab057a8c86cfcd121cb06aca8195e288.png

支付宝打赏

感谢您对作者surfin的打赏,我们会更加努力!    如果您想成为作者,请点我

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值