pdo_pgsql is different from pdo_mysql

pdo_pgsql and pdo_mysql are database drivers for PDO, and they provide the same PDO interface, but have important differences in underlying connectivity and feature support.

book 1.jpg

 Similarities ✅

 1. Same PDO interface

// is used consistently, both PostgreSQL and MySQL
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([1]);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

2. Same core method

- 'prepare()', 'execute()', 'fetch()', 'fetchAll()'

- `beginTransaction()`, `commit()`, `rollback()`

- `lastInsertId()`, `errorInfo()`

 3. The same preprocessing statement supports

 Main differences ❌

 1. Connecting DSN formats are different

// PostgreSQL
$dsn = "pgsql:host=localhost; port=5432; dbname=mydb; user=postgres; password=secret";
// MySQL
$dsn = "mysql:host=localhost; port=3306; dbname=mydb; charset=utf8mb4";

2. SQL syntax difference

- LIMIT/OFFSET syntax is the same (both support 'LIMIT ?) OFFSET ?')

- Quotation mark identifiers: PostgreSQL uses double quotes, MySQL uses backtick

marks

- Data types: PostgreSQL has unique types such as arrays and JSONB

- Function differences: date functions, string functions, etc

 3. Preprocessing statements are implemented differently

// PostgreSQL supports naming parameters and question mark placeholders
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id OR name = ?");
 MySQL also supports it, but the underlying implementation mechanism is different

4. Transaction isolation level

-- PostgreSQL supports more levels of isolation
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
-- MySQL's  InnoDB also supports it, but the implementation is different

5. LAST_INSERT_ID()

// PostgreSQL - Sequence name needs to be specified
$lastId = $pdo->lastInsertId('users_id_seq');
 MySQL - Automatic fetching
$lastId = $pdo->lastInsertId();

6. Return result processing

// PostgreSQL returns a boolean value that may be 't'/'f'
$bool = $result['is_active'];   Conversion may be required
 MySQL typically returns 1/0 or true/false

code example comparison

 Connecting to the database

// PostgreSQL connection
$pdo_pg = new PDO(
    "pgsql:host=localhost; dbname=testdb",
    "username",
    "password",
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
 MySQL connection
$pdo_mysql = new PDO(
    "mysql:host=localhost; dbname=testdb; charset=utf8mb4",
    "username",
    "password",
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);

get the last insert ID

// PostgreSQL
$stmt = $pdo_pg->prepare("INSERT INTO users (name) VALUES (?)  RETURNING id");
$stmt->execute(['John']);
$id = $stmt->fetchColumn();    Use the RETURNING clause
// MySQL
$pdo_mysql->exec("INSERT INTO users (name) VALUES ('John')");
$id = $pdo_mysql->lastInsertId();

best practice suggestions

 1. Use an abstract layer

// Create a database adapter
class Database {
    private $pdo;
    
    public function __construct($type, $config) {
        if ($type === 'pgsql') {
            $dsn = "pgsql:host={$config['host']}; dbname={$config['dbname']}";
        } else {
            $dsn = "mysql:host={$config['host']}; dbname={$config['dbname']}; charset=utf8mb4";
        }
        $this->pdo = new PDO($dsn, $config['user'], $config['pass']);
    }
    
     Unified method interface
    public function insert($table, $data) {
         Handle database discrepancies
    }
}

2. Avoid database-specific syntax

 -- bad: Use database-specific functions
SELECT DATE_FORMAT(created_at, '%Y-%m-%d') FROM users;  -- MySQL
SELECT TO_CHAR(created_at, 'YYYY-MM-DD') FROM users;    -- PostgreSQL
-- Okay: Let PHP handle the format conversion
SELECT created_at FROM users;
 Format Dates in PHP

3. Use a query builder

Consider using Doctrine DBAL, Laravel's query builder, etc., which can automatically handle database differences.

summary

Featurespdo_pgsqlpdo_mysql
DSN format`pgsql:` `mysql:`
port default54323306
quote identifierdouble quotes '"'<<>td width="283" valign="top" style="word-break: break-all; text-align: justify;">backtick marks' 
insert IDsequence is requiredautomatically fetched
Boolean returns 't'/'f' 1/0
array typeSupportnot supported
 JSON typenatively supportMySQL 5.7+ supports

Core recommendation: While PDO provides a unified interface, writing portable code avoids database-specific SQL syntax. If your project needs to switch databases, you should use a database abstraction layer or ORM.

分享給朋友:

“pdo_pgsql is different from pdo_mysql” 的相關文章

星空特效的HTML代碼示例

星空特效的HTML代碼示例

以下是一個星空特效的HTML代碼示例:這個代碼會在頁面背景中生成100個閃爍的星星,使得整個頁面看起來像是夜空中的星空。可以在瀏覽器中運行查看效果。這些代碼可以在瀏覽器中運行並產生相應的星空特效。…

HTML標簽屬性大全及代碼例子

HTML標簽屬性大全及代碼例子

在HTML中,屬性是在標簽中使用的特殊命令,它們提供了額外的信息以更好地描述標簽的內容和行為。屬性名表示該屬性的名稱,而屬性值表示該屬性要設置的值。HTML標簽屬性有很多種類和用途,它們可以影響標簽的內容、顏色、尺寸、超鏈接、樣式、表單等方面。一些常見的HTML標簽屬性包括:class、id、style、href、src、alt、disabled、checked、selected等等。在學習HTML標簽屬性時,需要註意一些細節和常見錯誤。總而言之,HTML標簽屬性是控制網頁顯示和行為的重要方式。HTML標簽屬性是可以用於定義HTML元素的附加信息。…

html制作網頁教程技能及代碼例子

html制作網頁教程技能及代碼例子

而HTML作為網頁的標準語言,學習HTML制作網頁的基本技能則是入門網頁制作的必修課程。在這篇文章中,我們將為大家講解一份詳細的HTML制作網頁教程,幫助初學者快速掌握網頁制作技巧,實現自己的網站夢想。以下是一個基礎的HTML網頁制作教程,步驟如下:1. 創建網頁文件 首先,打開一個文本編輯器,如Windows中的記事本,macOS中的TextEdit等。然後,在編輯器中創建一個新文件,將文件後綴名改為.html,表示這是一個HTML網頁文件。2. 添加HTML基礎結構。3. 添加網頁內容。4. 保存文件並打開網頁。…

html5自學教程步驟及代碼例子

html5自學教程步驟及代碼例子

HTML5是最新的HTML標準,具有更多的功能和特性,讓網頁的制作更加靈活和多樣化。以下是HTML5自學教程的一些步驟:1. 學習HTML基礎知識。在深入學習HTML5之前,你需要先學習HTML的基礎知識,包括HTML文件結構、標簽、屬性和元素等。2. 熟悉HTML5的新特性。HTML5相比於之前的版本有許多新特性,如視頻和音頻標簽、畫布、地理位置、本地存儲等等。3. 編寫示例代碼。理論不如實踐,通過編寫一些簡單的網頁示例代碼,你可以更好地熟悉HTML5的知識點和語法規則。…

html5菜鳥教程學習基本步驟

html5菜鳥教程學習基本步驟

以下是HTML5的菜鳥教程:1. 概述和基礎知識 了解HTML5的概念和新特性;熟悉HTML文件結構、標簽、元素和屬性;掌握HTML5的語義化標簽。2. 視頻和音頻 學習如何在網頁中嵌入視頻和音頻,使用video和audio標簽;熟悉媒體控制、字幕等相關屬性。3. 畫布和圖像 掌握使用canvas繪制2D圖形;熟悉圖像處理技術,如像素控制、濾鏡等。4. 表單和輸入 學習HTML5表單元素的新特性,如日期、時間、搜索等;熟悉表單數據驗證、自動填充等功能。…

類的三種訪問權限代碼例子

類的三種訪問權限代碼例子

在大多數的面向對象編程語言中,類的訪問權限通常分為以下三種:1. Public(公有) Public指的是類的成員對所有其他的類和對象都是可見的,可以被其他類和對象隨意調用。這種訪問權限最為開放,常用於表示類的主要功能或核心業務。2. Protected(保護) Protected指的是類的成員僅對自身和其子類可見,其他類或對象無法直接訪問。3. Private(私有) Private指的是類的成員僅對自身可見,即其他對象無法訪問和修改。…