PHP 创建重用数据库连接函数 mysqli与PDO

 代码如下:

    有兴趣的可以测试下

     摘自于某书

     

 1 <? php
 2     
 3  public function dbConnect( $usertype, $connectionType = 'mysqli' ) {
 4         $host = 'localhost';
 5         $db = 'phpsols';
 6         if( $usertype == 'read') {
 7             $user = 'psread';
 8             $pwd = '123456';
 9         } else if ( $usertype == 'write' ) {
10             $user = 'pswrite';
11             $pwd = '123456';
12         } else {
13             exit( 'Unrecognized connection type' );
14         }
15         if( $connectionType == 'mysqli') {
16             return new mysqli( $host, $user, $pwd, $db ) or die( 'Cannot open database' );
17         } else {
18             try {
19                 return new PDO( "mysql:host=$host;dbname=$db", $user, $pwd );
20             } catch( PDOException $e ) {
21                 $e -> getMessage;
22                 echo 'Cannot connect to database';
23                 exit;
24             }
25         }
26     }
27     
28 ?>
原文地址:https://www.cnblogs.com/itafter/p/4097127.html