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” 的相關文章

mark元素的主要功能及在HTML5 中的使用mark元素例子

mark元素的主要功能及在HTML5 中的使用mark元素例子

`<mark>` 元素的主要功能是突出顯示文本中的重要部分或關鍵字。在 HTML5 標準中,`<mark>` 元素用於標記一個文檔或一個段落中需要突出顯示的文本。一旦在 HTML 文件中使用了 `<mark>` 元素,瀏覽器通常會使用黃色背景標記該元素的文本,在頁面渲染上具有很好的效果。`<mark>` 元素還可以用於添加額外的視覺標識,以使讀者更快地識別重要內容。通過指定不同的顏色樣式,可以將文本突出顯示,以吸引讀者的註意力。…

meter元素顏色,可以使用CSS樣式來設置顏色

meter元素顏色,可以使用CSS樣式來設置顏色

meter元素可以用於表示已知範圍內的度量值,可以使用CSS樣式來設置顏色。具體來說,可以使用 <code>::-webkit-meter-optimum-value, ::-moz-meter-bar, ::-webkit-meter-bar</code> 偽元素來設置顏色。下面的例子中,我們將 <code>meter</code>。上述代碼中,當 <code>meter</code> 元素的值在80時,最優值(optimum)的顏色為綠色;當值落在0~80之間時,表格的顏色為灰色。可以按照自己的需求設置這些顏色值。…

JS跳轉頁面代碼及例子

JS跳轉頁面代碼及例子

JS跳轉頁面是一種很常見的前端交互技術,下面是幾種跳轉頁面的方式:1. 直接修改 `window.location.href` 屬性,2. 使用 `window.location.replace` 方法,此方法會替換當前頁面歷史記錄,不會在瀏覽器歷史記錄中留下痕跡。3. 使用 `window.open` 方法在一個新的瀏覽器窗口或標簽頁中打開一個頁面,4. 如果你需要在某個時間間隔後自動跳轉到目標頁面,可以使用 `setTimeout` 函數。…

一個簡單的html結婚特效的代碼

一個簡單的html結婚特效的代碼

以下是一個簡單的html結婚特效的代碼:1. 使用html和css定義了一個結婚的基本樣式;2. 分別定義新娘和新郎,並使用background-image設置其背景圖;3. 定義一個心形圖案,並使用animation讓其跳動。…

用html和CSS3制作酷炫的導航欄代碼及例子

用html和CSS3制作酷炫的導航欄代碼及例子

使用HTML5和CSS3的新特性可以制作出很多酷炫的導航欄效果,例如下拉菜單、響應式導航欄、帶有動態效果的導航欄等等。下面以下拉菜單為例,具體步驟如下:1. 創建 HTML 結構;2. 設置基本樣式;3. 添加動態效果。這樣就可以制作出下拉菜單效果,當滑鼠懸停在菜單項上時,菜單項下面的下拉菜單顯示出來,同時菜單項上的箭頭指向上方,滑鼠移開時,下拉菜單消失。在此過程中,使用了CSS3的過渡效果和旋轉效果,使效果更加炫酷。  …

html零基礎入門教程及代碼演示例子

html零基礎入門教程及代碼演示例子

HTML是創建網頁的基礎語言。在互聯網的世界裏,網頁是我們獲取信息和與世界連接的主要途徑之一。因此,學習HTML是設計和制作網頁的重要一步。如果您是一個完全零基礎的人,那麼這份教程可以幫助您快速入門,並開始創建自己的網頁。在這個教程中,我們將探討HTML的基礎語法和標記,以及如何將它們組合在一起來構建一個簡單的網頁。無需任何預備知識,您只需要在計算機上安裝一個文本編輯器和瀏覽器,就可以開始學習HTML。讓我們開始!…