在使用pdo连接数据库之前,先要对pdo安装和配置
base.php如下:
<strong><span style="font-size:18px;"><?php header('content-type:text/html;charset=utf-8');//数组调试函数function show_bug($msg){ echo '<pre>'; print_r($msg); echo '</pre>';}?></span></strong>
1.pdo通过参数形式链接数据库
<strong><span style="font-size:18px;">include_once base.php;try{ //$dsn是数据源 $dsn='mysql:host=localhost;dbname=imooc'; $username='root'; $passwd=''; $pdo=new pdo($dsn,$username,$passwd); //如果连接成功的话,得到的是pdo的对象 show_bug($pdo);}catch(pdoexception $e){ echo $e->getmessage();}</span></strong>
2.pdo通过uri形式连接数据库
<strong><span style="font-size:18px;"><?php include_once "base.php";//pdo通过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通过配置文件形式连接数据库
<strong><span style="font-size:18px;"><?php include_once "base.php";//pdo通过配置文件形式连接数据库//在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>
以上三种,建议使用第一种,通过参数形式链接数据库的
【相关教程推荐】
1. php编程从入门到精通全套视频教程
2. php从入门到精通
3. bootstrap教程