The best PHP PDO Tutorial In 2024, In this tutorial you can learn PDO installation,
PHP Data Objects (PDO) extension defines a lightweight, consistent interface PHP database access.
PDO provides a data access abstraction layer, which means that, no matter what kind of database, you can query and retrieve data using the same functions (methods).
PDO with PHP5.1 issued in PHP5.0 the PECL extension may also be used, you can not run on earlier versions of PHP.
You can PHP's phpinfo () function to see if the PDO extension is installed.
In the Unix or Linux you need to add the following extensions:
extension=pdo.so
PDO and all the major drivers as shared extensions released with PHP, to activate them simply edit your php.ini file and add the following extensions:
extension=php_pdo.dllIn addition there are the following extensions corresponding to various databases:
;extension=php_pdo_firebird.dll ;extension=php_pdo_informix.dll ;extension=php_pdo_mssql.dll ;extension=php_pdo_mysql.dll ;extension=php_pdo_oci.dll ;extension=php_pdo_oci8.dll ;extension=php_pdo_odbc.dll ;extension=php_pdo_pgsql.dll ;extension=php_pdo_sqlite.dll
After set up these configurations, we need to restart PHP or Web server.
Next we look at their specific examples, the following examples use PDO to connect MySql database:
<?php $dbms='mysql'; //数据库类型 $host='localhost'; //数据库主机名 $dbName='test'; //使用的数据库 $user='root'; //数据库连接用户名 $pass=''; //对应的密码 $dsn="$dbms:host=$host;dbname=$dbName"; try { $dbh = new PDO($dsn, $user, $pass); //初始化一个PDO对象 echo "连接成功<br/>"; /*你还可以进行一次搜索操作 foreach ($dbh->query('SELECT * from FOO') as $row) { print_r($row); //你可以用 echo($GLOBAL); 来看到这些值 } */ $dbh = null; } catch (PDOException $e) { die ("Error!: " . $e->getMessage() . "<br/>"); } //默认这个不是长连接,如果需要数据库长连接,需要最后加一个参数:array(PDO::ATTR_PERSISTENT => true) 变成这样: $db = new PDO($dsn, $user, $pass, array(PDO::ATTR_PERSISTENT => true)); ?>
Very simple, then let us look at the specific PHP PDO specify: