Home >Backend Development >PHP Tutorial >Simple sample code for PDO operation in php

Simple sample code for PDO operation in php

怪我咯
怪我咯Original
2017-07-12 15:52:571241browse

PHP DataObject (PDO) extension defines a lightweight consistent interface for PHP to access the database.

PDO provides a data access abstraction layer, which means that no matter which database is used, the same functions (methods) can be used to query and obtain data.

PDO is released with PHP5.1 and can also be used in the PECL extension of PHP5.0. It cannot run on previous PHP versions.

This article mainly introduces PHP's PDO operations. It analyzes the simple connection, initialization, query, insertion and other operation techniques of PHP's PDO operations in the form of simple examples. Friends in need can refer to it. Next, Here I encapsulate all operations of PDO into a class for easy operation.

The class code is as follows:

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();
  }
}

Usage:

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 supports SQL statements to be called as parameters, which can effectively prevent SQL injection.

The above is the detailed content of Simple sample code for PDO operation in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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