Heim  >  Artikel  >  Backend-Entwicklung  >  PHP的PDO操作简单示例_php技巧

PHP的PDO操作简单示例_php技巧

WBOY
WBOYOriginal
2016-05-16 19:55:161451Durchsuche

本文实例讲述了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();
  }
}

使用方法:

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;

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

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

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

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn