PHP的PDO操作简单示例

时间:2021-07-28 06:26:24

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

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

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

类代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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();
  }
}

使用方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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程序设计有所帮助。