PDO擴展為PHP訪問資料庫定義了一個輕量級的、一致性的接口,它提供了一個資料存取抽象層,這樣,無論使用什麼資料庫,都可以透過一致的函數執行查詢和獲取資料。
PDO隨PHP5.1發行,在PHP5.0的PECL擴充中也可以使用,無法運作於先前的PHP版本。
在PDO出現之間,在PHP中連接資料庫的函數根據資料庫的不同而不同。
例如,MySQL用 mysql_connect 函數, PostgreSQL資料庫用 pg_connect 函數。
透過PDO編寫的程式碼,未來資料庫發生變化,只需要適當修改資料庫的連線參數,不需要修改邏輯程式碼即可。
PDO和主要資料庫的驅動同PHP一起作為擴展發布,要激活它們只需簡單的編輯php.ini檔案: extension=php_pdo.dll
然後,選擇針對特定資料庫的DLL檔案使用dl() 在運行時加載,或在php.ini檔案中php_pdo.dll 行後啟用它們,如:
<code><span>extension=<span>php_pdo.dll</span></span><span>extension=<span>php_pdo_mysql.dll</span></span><span>extension=<span>php_pdo_pgsql.dll</span></span><span>extension=<span>php_pdo_sqlite.dll</span></span></code>
<code><span>$dsn</span> = <span>'mysql:dbname=yii2test;host=localhost'</span>; <span>$user</span> = <span>'sqluser'</span>; <span>$password</span> = <span>'sqlpassword'</span>; <span>$db</span> = <span>new</span> PDO(<span>$dsn</span>, <span>$user</span>, <span>$password</span>); <span>try</span>{ <span>$dbh</span> = <span>new</span> PDO(<span>$dsn</span>, <span>$user</span>, <span>$password</span>); }<span>catch</span> (PDOException <span>$e</span>){ <span>print</span>(<span>'Error:'</span>.<span>$e</span>->getMessage()); <span>die</span>(); }</code>
<code><span>$dsn</span> = <span>'pgsql:dbname=yii2test host=localhost port=5432'</span>; <span>$user</span> = <span>'sqluser'</span>; <span>$password</span> = <span>'sqlpassword'</span>; <span>try</span>{ <span>$dbh</span> = <span>new</span> PDO(<span>$dsn</span>, <span>$user</span>, <span>$password</span>); }<span>catch</span> (PDOException <span>$e</span>){ <span>print</span>(<span>'Error:'</span>.<span>$e</span>->getMessage()); <span>die</span>(); }</code>
<code><span>$dsn</span> = <span>'sqlite:d:/sqlite/yii2test.db'</span>; <span>$user</span> = <span>''</span>; <span>$password</span> = <span>''</span>; <span>try</span>{ <span>$dbh</span> = <span>new</span> PDO(<span>$dsn</span>, <span>$user</span>, <span>$password</span>); }<span>catch</span> (PDOException <span>$e</span>){ <span>print</span>(<span>'Error:'</span>.<span>$e</span>->getMessage()); <span>die</span>(); }</code>版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。
以上就介紹了PDO學習筆記,包含了方面的內容,希望對PHP教學有興趣的朋友有幫助。