PHP의 PDO

小云云
풀어 주다: 2023-03-22 20:16:02
원래의
12708명이 탐색했습니다.

PHP PDO란 무엇인가요?

PDO(PHP Data Objects)는 PHP에서 데이터베이스에 연결하기 위한 인터페이스입니다. PDO와 mysqli는 데이터베이스 사용 보안을 기반으로 원래 PHP에서 사용했던 mysql 관련 기능을 대체하도록 권장되었습니다. 왜냐하면 후자에는 SQL 삽입에 대한 보호 기능이 부족했기 때문입니다.

PDO(PHP Data Objects) 확장은 PHP가 데이터베이스에 액세스할 수 있는 가볍고 일관된 인터페이스를 정의합니다. PDO 인터페이스를 구현하는 각 데이터베이스 드라이버는 데이터베이스 관련 기능을 표준 확장으로 노출할 수 있습니다. PDO 확장을 사용한다고 해서 데이터베이스 기능이 자체적으로 구현되는 것은 아닙니다. 데이터베이스 서비스에 액세스하려면 데이터베이스별 PDO 드라이버를 사용해야 합니다.

추천 mysql 비디오 튜토리얼: "mysql tutorial"

PDO는 데이터 액세스 추상화 계층을 제공합니다. 즉, 어떤 데이터베이스를 사용하든 동일한 기능(메서드)을 사용하여 데이터를 쿼리하고 얻을 수 있습니다. PDO는 데이터베이스 추상화 계층을 제공하지 않으며 SQL을 다시 작성하지 않으며 누락된 기능을 에뮬레이트하지도 않습니다. 필요한 경우 성숙한 추상화 계층을 사용해야 합니다.

데이터베이스 지원:

  • firebird

  • informix

  • mysql

  • mssql

  • odbc

  • pgsql

  • sqlite

PHP PDO 오류 오류 처리

PDO는 다양한 애플리케이션 개발 스타일을 충족하기 위해 세 가지 오류 처리 모드를 제공합니다.

PDO::ERRMODE_SILENT

이것이 기본 모드입니다. PDO는 단순히 오류 코드를 설정하며 이는 명령문 및 데이터베이스 개체에 대한 PDO::errorCode() 및 PDO::errorInfo() 메서드를 사용하여 확인할 수 있습니다. 명령문 객체 호출로 인해 오류가 발생하는 경우 해당 객체의 PDOStatement::errorCode() 또는 PDOStatement::errorInfo() 메서드를 호출할 수 있습니다. 데이터베이스 개체를 호출하여 오류가 발생한 경우 데이터베이스 개체에 대해 위의 두 메서드를 호출할 수 있습니다.

PDO::ERRMODE_WARNING

PDO는 오류 코드 설정 외에도 기존 E_WARNING 메시지도 보냅니다. 이 설정은 애플리케이션 흐름을 방해하지 않고 무엇이 잘못되었는지 확인하려는 경우 디버깅/테스트 중에 유용합니다.

PDO::ERRMODE_EXCEPTION

PDO는 오류 코드 설정 외에도 PDOException 예외 클래스를 발생시키고 해당 속성을 설정하여 오류 코드 및 오류 정보를 반영합니다. 이 설정은 디버깅 중에도 매우 유용합니다. 오류가 발생한 스크립트 지점을 효과적으로 확대하여 코드에서 잠재적인 문제가 있는 영역을 매우 빠르게 찾아낼 수 있기 때문입니다. (기억: 예외로 인해 스크립트가 종료되면 트랜잭션은 자동으로 롤백됩니다.

예외 모드의 또 다른 매우 유용한 점은 기존 PHP 스타일 경고보다 더 명확하게 자체 오류 처리를 구축할 수 있다는 점이며, 자동 모드 및 각 데이터베이스 호출의 반환 값을 명시적으로 확인하는 것과 비교할 때 예외 모드에는 코드/중첩이 덜 필요합니다.

PHP PDO는

을 사용하여 MySQL

<?php

$type = &#39;mysql&#39;;
$hostname = &#39;localhost&#39;;
$dbname = &#39;test&#39;;
$username = &#39;root&#39;;
$password = &#39;root&#39;;

try {

    $dsn = sprintf(&#39;%s:dbname=%s;host=%s&#39;, $type, $dbname, $dbname);

    //初始化一个PDO对象
    $pdo = new PDO($dsn, $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION //开启异常模式
    ]);

} catch (PDOException $e) {
    die ("Database error: " . $e->getMessage());
}

?>
로그인 후 복사

쿼리 데이터

$type = &#39;mysql&#39;;
$hostname = &#39;127.0.0.1&#39;;
$dbname = &#39;test&#39;;
$username = &#39;root&#39;;
$password = &#39;root&#39;;

try {

    $dsn = sprintf(&#39;%s:dbname=%s;host=%s;charset=utf8&#39;, $type, $dbname, $hostname);

    //初始化一个PDO对象
    $pdo = new PDO($dsn, $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION //开启异常模式
    ]);

} catch (PDOException $e) {
    die ("Database error: " . $e->getMessage());
}

$smt = $pdo->query(&#39;SELECT * FROM t_user&#39;);

$data = $smt->fetchAll(PDO::FETCH_ASSOC);

var_dump($data);
로그인 후 복사

결과 인쇄

array(5) {
  [0]=>
  array(4) {
    ["password"]=>
    string(8) "jidasdas"
    ["phone"]=>
    string(9) "888888888"
    ["user_id"]=>
    string(32) "402881e564c0da7b0164c11adc8f0006"
    ["user_name"]=>
    string(5) "marry"
  }
  [1]=>
  array(4) {
    ["password"]=>
    string(4) "tiyv"
    ["phone"]=>
    string(6) "000000"
    ["user_id"]=>
    string(32) "402881e564c0da7b0164c1227c5d000b"
    ["user_name"]=>
    string(6) "Bliabx"
  }
  [2]=>
  array(4) {
    ["password"]=>
    string(5) "dsada"
    ["phone"]=>
    string(7) "3123123"
    ["user_id"]=>
    string(32) "402881e764bbd6340164bbd6af4e0001"
    ["user_name"]=>
    string(4) "Nusg"
  }
  [3]=>
  array(4) {
    ["password"]=>
    string(4) "kjhk"
    ["phone"]=>
    string(6) "321312"
    ["user_id"]=>
    string(32) "402881e764bbd7b60164bbd9c3cb0002"
    ["user_name"]=>
    string(6) "XIoaji"
  }
  [4]=>
  array(4) {
    ["password"]=>
    string(3) "dsa"
    ["phone"]=>
    string(3) "110"
    ["user_id"]=>
    string(32) "402881e764bbed9f0164bbee12c70000"
    ["user_name"]=>
    string(6) "Villig"
  }
}
로그인 후 복사

전처리

/* 通过数组值向预处理语句传递值 */
$sql = &#39;SELECT name, colour, calories FROM fruit WHERE calories < :calories AND colour = :colour&#39;;

$sth = $dbh->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);

$sth->execute([&#39;:calories&#39; => 150, &#39;:colour&#39; => &#39;red&#39;]);

$red = $sth->fetchAll();

$sth->execute([&#39;:calories&#39; => 175, &#39;:colour&#39; => &#39;yellow&#39;]);

$yellow = $sth->fetchAll();
로그인 후 복사

기본 PDO 패키지

<?php
/**
* DAOPDO
* @authors by houzhyan <houzhyan@126.com>
* @blog http://www.descartes.top/
* @version >5.1 utf8
*/
class DAOPDO
{
    protected static $_instance = null;
    protected $dbName = &#39;&#39;;
    protected $dsn;
    protected $dbh;
    
    /**
     * 构造
     * 
     * @return DAOPDO
     */
    private function __construct($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset)
    {
        try {
            $this->dsn = &#39;mysql:host=&#39;.$dbHost.&#39;;dbname=&#39;.$dbName;
            $this->dbh = new PDO($this->dsn, $dbUser, $dbPasswd);
            $this->dbh->exec(&#39;SET character_set_connection=&#39;.$dbCharset.&#39;, character_set_results=&#39;.$dbCharset.&#39;, character_set_client=binary&#39;);
        } catch (PDOException $e) {
            $this->outputError($e->getMessage());
        }
    }
    
    /**
     * 防止克隆
     * 
     */
    private function __clone() {}
    
    /**
     * Singleton instance
     * 
     * @return Object
     */
    public static function getInstance($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset)
    {
        if (self::$_instance === null) {
            self::$_instance = new self($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset);
        }
        return self::$_instance;
    }
    
    /**
     * Query 查询
     *
     * @param String $strSql SQL语句
     * @param String $queryMode 查询方式(All or Row)
     * @param Boolean $debug
     * @return Array
     */
    public function query($strSql, $queryMode = &#39;All&#39;, $debug = false)
    {
        if ($debug === true) $this->debug($strSql);
        $recordset = $this->dbh->query($strSql);
        $this->getPDOError();
        if ($recordset) {
            $recordset->setFetchMode(PDO::FETCH_ASSOC);
            if ($queryMode == &#39;All&#39;) {
                $result = $recordset->fetchAll();
            } elseif ($queryMode == &#39;Row&#39;) {
                $result = $recordset->fetch();
            }
        } else {
            $result = null;
        }
        return $result;
    }
    
    /**
     * Update 更新
     *
     * @param String $table 表名
     * @param Array $arrayDataValue 字段与值
     * @param String $where 条件
     * @param Boolean $debug
     * @return Int
     */
    public function update($table, $arrayDataValue, $where = &#39;&#39;, $debug = false)
    {
        $this->checkFields($table, $arrayDataValue);
        if ($where) {
            $strSql = &#39;&#39;;
            foreach ($arrayDataValue as $key => $value) {
                $strSql .= ", `$key`=&#39;$value&#39;";
            }
            $strSql = substr($strSql, 1);
            $strSql = "UPDATE `$table` SET $strSql WHERE $where";
        } else {
            $strSql = "REPLACE INTO `$table` (`".implode(&#39;`,`&#39;, array_keys($arrayDataValue))."`) VALUES (&#39;".implode("&#39;,&#39;", $arrayDataValue)."&#39;)";
        }
        if ($debug === true) $this->debug($strSql);
        $result = $this->dbh->exec($strSql);
        $this->getPDOError();
        return $result;
    }
    
    /**
     * Insert 插入
     *
     * @param String $table 表名
     * @param Array $arrayDataValue 字段与值
     * @param Boolean $debug
     * @return Int
     */
    public function insert($table, $arrayDataValue, $debug = false)
    {
        $this->checkFields($table, $arrayDataValue);
        $strSql = "INSERT INTO `$table` (`".implode(&#39;`,`&#39;, array_keys($arrayDataValue))."`) VALUES (&#39;".implode("&#39;,&#39;", $arrayDataValue)."&#39;)";
        if ($debug === true) $this->debug($strSql);
        $result = $this->dbh->exec($strSql);
        $this->getPDOError();
        return $result;
    }
    
    /**
     * Replace 覆盖方式插入
     *
     * @param String $table 表名
     * @param Array $arrayDataValue 字段与值
     * @param Boolean $debug
     * @return Int
     */
    public function replace($table, $arrayDataValue, $debug = false)
    {
        $this->checkFields($table, $arrayDataValue);
        $strSql = "REPLACE INTO `$table`(`".implode(&#39;`,`&#39;, array_keys($arrayDataValue))."`) VALUES (&#39;".implode("&#39;,&#39;", $arrayDataValue)."&#39;)";
        if ($debug === true) $this->debug($strSql);
        $result = $this->dbh->exec($strSql);
        $this->getPDOError();
        return $result;
    }
    
    /**
     * Delete 删除
     *
     * @param String $table 表名
     * @param String $where 条件
     * @param Boolean $debug
     * @return Int
     */
    public function delete($table, $where = &#39;&#39;, $debug = false)
    {
        if ($where == &#39;&#39;) {
            $this->outputError("&#39;WHERE&#39; is Null");
        } else {
            $strSql = "DELETE FROM `$table` WHERE $where";
            if ($debug === true) $this->debug($strSql);
            $result = $this->dbh->exec($strSql);
            $this->getPDOError();
            return $result;
        }
    }
    
    /**
     * execSql 执行SQL语句,debug=>true可打印sql调试
     *
     * @param String $strSql
     * @param Boolean $debug
     * @return Int
     */
    public function execSql($strSql, $debug = false)
    {
        if ($debug === true) $this->debug($strSql);
        $result = $this->dbh->exec($strSql);
        $this->getPDOError();
        return $result;
    }
    
    /**
     * 获取字段最大值
     * 
     * @param string $table 表名
     * @param string $field_name 字段名
     * @param string $where 条件
     */
    public function getMaxValue($table, $field_name, $where = &#39;&#39;, $debug = false)
    {
        $strSql = "SELECT MAX(".$field_name.") AS MAX_VALUE FROM $table";
        if ($where != &#39;&#39;) $strSql .= " WHERE $where";
        if ($debug === true) $this->debug($strSql);
        $arrTemp = $this->query($strSql, &#39;Row&#39;);
        $maxValue = $arrTemp["MAX_VALUE"];
        if ($maxValue == "" || $maxValue == null) {
            $maxValue = 0;
        }
        return $maxValue;
    }
    
    /**
     * 获取指定列的数量
     * 
     * @param string $table
     * @param string $field_name
     * @param string $where
     * @param bool $debug
     * @return int
     */
    public function getCount($table, $field_name, $where = &#39;&#39;, $debug = false)
    {
        $strSql = "SELECT COUNT($field_name) AS NUM FROM $table";
        if ($where != &#39;&#39;) $strSql .= " WHERE $where";
        if ($debug === true) $this->debug($strSql);
        $arrTemp = $this->query($strSql, &#39;Row&#39;);
        return $arrTemp[&#39;NUM&#39;];
    }
    
    /**
     * 获取表引擎
     * 
     * @param String $dbName 库名
     * @param String $tableName 表名
     * @param Boolean $debug
     * @return String
     */
    public function getTableEngine($dbName, $tableName)
    {
        $strSql = "SHOW TABLE STATUS FROM $dbName WHERE Name=&#39;".$tableName."&#39;";
        $arrayTableInfo = $this->query($strSql);
        $this->getPDOError();
        return $arrayTableInfo[0][&#39;Engine&#39;];
    }
    //预处理执行
    public function prepareSql($sql=&#39;&#39;){
        return $this->dbh->prepare($sql);
    }
    //执行预处理
    public function execute($presql){
        return $this->dbh->execute($presql);
    }
 
/**
 * pdo属性设置
 */
    public function setAttribute($p,$d){
        $this->dbh->setAttribute($p,$d);
    }
 
    /**
     * beginTransaction 事务开始
     */
    public function beginTransaction()
    {
        $this->dbh->beginTransaction();
    }
    
    /**
     * commit 事务提交
     */
    public function commit()
    {
        $this->dbh->commit();
    }
    
    /**
     * rollback 事务回滚
     */
    public function rollback()
    {
        $this->dbh->rollback();
    }
    
    /**
     * transaction 通过事务处理多条SQL语句
     * 调用前需通过getTableEngine判断表引擎是否支持事务
     *
     * @param array $arraySql
     * @return Boolean
     */
    public function execTransaction($arraySql)
    {
        $retval = 1;
        $this->beginTransaction();
        foreach ($arraySql as $strSql) {
            if ($this->execSql($strSql) == 0) $retval = 0;
        }
        if ($retval == 0) {
            $this->rollback();
            return false;
        } else {
            $this->commit();
            return true;
        }
    }
 
    /**
     * checkFields 检查指定字段是否在指定数据表中存在
     *
     * @param String $table
     * @param array $arrayField
     */
    private function checkFields($table, $arrayFields)
    {
        $fields = $this->getFields($table);
        foreach ($arrayFields as $key => $value) {
            if (!in_array($key, $fields)) {
                $this->outputError("Unknown column `$key` in field list.");
            }
        }
    }
    
    /**
     * getFields 获取指定数据表中的全部字段名
     *
     * @param String $table 表名
     * @return array
     */
    private function getFields($table)
    {
        $fields = array();
        $recordset = $this->dbh->query("SHOW COLUMNS FROM $table");
        $this->getPDOError();
        $recordset->setFetchMode(PDO::FETCH_ASSOC);
        $result = $recordset->fetchAll();
        foreach ($result as $rows) {
            $fields[] = $rows[&#39;Field&#39;];
        }
        return $fields;
    }
    
    /**
     * getPDOError 捕获PDO错误信息
     */
    private function getPDOError()
    {
        if ($this->dbh->errorCode() != &#39;00000&#39;) {
            $arrayError = $this->dbh->errorInfo();
            $this->outputError($arrayError[2]);
        }
    }
    
    /**
     * debug
     * 
     * @param mixed $debuginfo
     */
    private function debug($debuginfo)
    {
        var_dump($debuginfo);
        exit();
    }
    
    /**
     * 输出错误信息
     * 
     * @param String $strErrMsg
     */
    private function outputError($strErrMsg)
    {
        throw new Exception(&#39;MySQL Error: &#39;.$strErrMsg);
    }
    
    /**
     * destruct 关闭数据库连接
     */
    public function destruct()
    {
        $this->dbh = null;
    }
   /**
    *PDO执行sql语句,返回改变的条数
    *如需调试可选用execSql($sql,true)
    */
    public function exec($sql=&#39;&#39;){
        return $this->dbh->exec($sql);
    }
}
?>
로그인 후 복사

PHP PDO 자세한 설명에 연결합니다.

PDO 수업

PDO::beginTransaction — 트랜잭션 시작

PDO::commit — 트랜잭션 커밋

PDO::__construct — 데이터베이스 연결을 나타내는 PDO 인스턴스 생성

PDO::errorCode — 마지막 작업과 관련된 SQLSTATE 가져오기 데이터베이스 핸들

PDO::errorInfo — 마지막 데이터베이스 작업의 오류 메시지를 반환합니다.

PDO::exec — SQL 문을 실행하고 영향을 받은 행 수를 반환합니다.

PDO::getAttribute — 데이터베이스의 속성을 검색합니다. Connection

PDO::getAvailableDrivers — 사용 가능한 드라이버 배열을 반환합니다.

PDO::inTransaction — 트랜잭션 내에 있는지 확인합니다.

PDO::lastInsertId — 마지막으로 삽입된 행의 ID 또는 시퀀스 값을 반환합니다.

PDO::prepare — SQL 문 실행을 준비하고 PDOStatement 개체를 반환합니다.

PDO::query — SQL 문을 실행하고 결과 집합으로 이해할 수 있는 PDOStatement 개체를 반환합니다.

PDO::quote — 문자열에 따옴표를 추가합니다. SQL문.

PDO::rollBack — 트랜잭션 롤백

PDO::setAttribute — 속성 설정

PDOStatement 클래스

PDOStatement::bindColumn — 열을 PHP 변수에 바인딩

PDOStatement::bindParam — Parameter 바인딩 지정된 변수 이름에

PDOStatement::bindValue — 값을 매개변수에 바인딩합니다.

PDOStatement::closeCursor — 명령문을 다시 실행할 수 있도록 커서를 닫습니다.

PDOStatement::columnCount — 결과 집합의 열 수를 반환합니다.

PDOStatement::debugDumpParams — SQL 전처리 명령을 인쇄합니다.

PDOStatement::errorCode — 마지막 문 핸들 작업과 관련된 SQLSTATE를 가져옵니다.

PDOStatement:: errorInfo — 마지막 명령문 핸들 작업과 관련된 확장 오류 정보 가져오기

PDOStatement::execute — 준비된 명령문 실행

PDOStatement::fetch — 결과 집합에서 다음 행 가져오기

PDOStatement::fetchAll — 다음을 포함하는 목록 반환 결과 집합의 모든 결과 행 배열

PDOStatement::fetchColumn — 결과 집합의 다음 행에서 단일 열을 반환합니다.

PDOStatement::fetchObject — 다음 줄을 가져와서 객체로 반환합니다.

PDOStatement::getAttribute — 문 속성 검색

PDOStatement::getColumnMeta — 결과 집합의 열에 대한 메타데이터 반환

PDOStatement::nextRowset — 다중 행 집합 문 핸들에서 다음 행 집합으로 이동

PDOStatement: :rowCount — 이전 SQL 문에 의해 영향을 받은 행 수를 반환합니다.

PDOStatement::setAttribute — 문 속성을 설정합니다.

PDOStatement::setFetchMode — 문에 대한 기본 가져오기 모드를 설정합니다.

위 내용은 PHP의 PDO의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
php
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!