The appearance of PDO is to solve the problem that the connection between PHP and each database has its own function, and its high abstraction makes it extremely convenient to use. Because the most common collocation is php+mysql, so here is the example of connecting Mysql. first, the Parameter form
[PHP]View Plaincopyprint?
- try{
- $dsn = ' Mysql:host=localhost;dbname=myblog ';
- $username = ' root ';
- $passwd = ' 123456 ';
- $pdo = new PDO ($dsn, $username, $passwd);
- Var_dump ($pdo);
- }catch (pdoexception $e) {
- echo $e->getmessage ();
- }
try{$dsn = ' Mysql:host=localhost;dbname=myblog '; $username = ' root '; $passwd = ' 123456 '; $pdo = new PDO ($ DSN, $username, $passwd); Var_dump ($PDO);} catch (Pdoexception $e) {echo $e->getmessage ();}
second, the URI form
[PHP]View Plaincopyprint?
- try{
- $dsn = ' uri:file://f:\wamp\www\myblog\dsn.txt ';
- $username = ' root ';
- $passwd = ' 123456 ';
- $pdo = new PDO ($dsn, $username, $passwd);
- Var_dump ($pdo);
- }catch (pdoexception $e) {
- echo $e->getmessage ();
- }
- Dsn.txt
- Mysql:host=localhost;dbname=myblog
try{$dsn = ' uri:file://f:\wamp\www\myblog\dsn.txt '; $username = ' root '; $passwd = ' 123456 '; $pdo
Third, the configuration file mode
[PHP]View Plaincopyprint?
- try{
- $dsn = ' Mypdo ';
- $username = ' root ';
- $passwd = ' 123456 ';
- $pdo = new PDO ($dsn, $username, $passwd);
- Var_dump ($pdo);
- }catch (pdoexception $e) {
- echo $e->getmessage ();
- }
- Add the following code anywhere in the php.ini file, and save the restart server
- pdo.dsn.mypdo="Mysql:host=localhost;dbname=myblog"
try{$dsn = ' mypdo '; $username = ' root '; $passwd = ' 123456 '; $pdo = new PDO ($DSN, $username, $passwd); var_dump ($PDO);} catch (Pdoexception $e) {echo $e->getmessage ();} Where you add the following code anywhere in the php.ini file, and save the restart server pdo.dsn.mypdo= "Mysql:host=localhost;dbname=myblog"
Three ways to connect a database with PDO