Before using PDO to connect to a database, install and configure the PDO
Base. PHP is as follows:
[PHP]View PlainCopy
- <strong><span style="FONT-SIZE:18PX;" ><?php
- Header (' Content-type:text/html;charset=utf-8 ');
- Array Debug functions
- function Show_bug ($msg) {
- echo ' <pre> ';
- Print_r ($msg);
- echo ' </pre> ';
- }
- ?></span></strong>
1.pdo linking the database via parametric form
[HTML]View PlainCopy
- <strong><span style="FONT-SIZE:18PX;" >include_once "base.php";
- try{
- $DSN is the data source
- $dsn=' MYSQL:HOST=LOCALHOST;DBNAME=IMOOC ';
- $username=' root ';
- $passwd=';
- $pdo=New PDO ($DSN, $username, $passwd);
- If the connection is successful, you get the PDO object.
- Show_bug ($PDO);
- }catch (Pdoexception $e) {
- Echo $e->getmessage ();
- }</span></strong>
2.pdo connecting the database by URI
Create a new Dsn.txt file with the following:
[PHP]View PlainCopy
- <strong><span style="FONT-SIZE:18PX;" ><?php
- Include_once "base.php";
- PDO connects to database by URI
- try{
- $dsn =' uri:file://d:\wamp\www\muke\pdo\dsn.txt ';
- $username =' root ';
- $passwd =";
- $pdo =new PDO ($dsn,$username,$passwd);
- Show_bug ($pdo);
- }catch (pdoexception $e) {
- echo $e->getmessage ();
- }
- ?></span></strong>
3.pdo connect to the database as a configuration file
[PHP]View PlainCopy
- <strong><span style="FONT-SIZE:18PX;" ><?php
- Include_once "base.php";
- PDO connects to a database by configuration file form
- Configuring in PHP.ini
- try{
- $dsn =' Imooc ';
- $username =' root ';
- $passwd =";
- $pdo =new PDO ($dsn,$username,$passwd);
- Show_bug ($pdo);
- }catch (pdoexception $e) {
- echo $e->getmessage ();
- }
- ?></span></strong>
Of the above three kinds, we recommend using the first, through the Parameter form link database
Three ways to connect the PDO database