Home > Backend Development > PHP Tutorial > PHP的PDO操作简单示例_PHP

PHP的PDO操作简单示例_PHP

WBOY
Release: 2016-05-27 10:35:31
Original
1124 people have browsed it

本文实例讲述了PHP的简单PDO操作。分享给大家供大家参考,具体如下:

网上关于PDO的资料很多。这里就不累赘了。

这里我将PDO所有操作封装到一个类里方便操作。

类代码如下:

class DB {
  //pdo对象
  public $con = NULL;
  function DB()
  {
    $this->con = new PDO("mysql:host=127.0.0.1;dbname=dbtest", "root", "xxx", array(
      PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES `utf8`',
      PDO::ATTR_PERSISTENT => TRUE,
    ));
    $this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $this->con->setAttribute(PDO::ATTR_CASE, PDO::CASE_UPPER);
  }
  public function query($sql, $para = NULL)
  {
    $sqlType = strtoupper(substr($sql, 0, 6));
    $cmd = $this->con->prepare($sql);
    if($para != NULL)
    {
      $cmd->execute($para);
    }
    else
    {
      $cmd->execute();
    }
    if($sqlType == "SELECT")
    {
      return $cmd->fetchAll(); 
    }
    if($sqlType == "INSERT")
    {
      return $this->con->lastInsertId();
    }
    return $cmd->rowCount();
  }
}

Copy after login

使用方法:

include "pdo.php";
$db = new DB();
$subjectList = $db->query("SELECT * FROM `table1`");
$count = $db->query("UPDATE `table1` SET `name` = 'test' WHERE `id` = :id", array(':id' => 795));
try
{
  echo $db->con->beginTransaction();
  $count = $db->con->exec("UPDATE `table1` SET `name` = 'test1' WHERE `id` = 795");
  $count = $db->con->exec("UPDATE `table1` SET `name1` = 'test22' WHERE `id` = 795");
  $count = $db->con->exec("UPDATE `table1` SET `name1` = 'test333' WHERE `id` = 795");
  echo $db->con->commit();
}
catch (Exception $e)
{
  // MYSQL 的表类型 InnoDB(支持事务) MyISAM(不支持事务)
  echo $db->con->rollBack();
  throw new MyException("事务测试错误", $e);
}
$db = NULL;

Copy after login

PDO支持SQL语句以参数方式调用,可有效的防止SQL注入。

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《php操作office文档技巧总结(包括word,excel,access,ppt)》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template