<?php header("Content-Type: text/html;charset=utf-8"); // $pdo = new PDO('mysql:host=127.0.0.1;dbname=ouyangke', 'root', 'root'); // $pdo = new PDO('mysql:host=127.0.0.1;dbname=chenqingxuan','root','cqx07231950'); $db = [ 'type' => 'mysql', 'host' => '127.0.0.1', 'dbname' => 'chenqingxuan', 'username' => 'root', 'password' => 'cqx07231950' ]; $dsn = $db['type'].':host='.$db['host'].';dbname='.$db['dbname']; $pdo = new PDO($dsn,$db['username'],$db['password']); // var_dump($pdo); 数组和对象不能被echo打印 // 连接后的返回值,保存在pdo变量里 一直存在直至代码结束。 $sql = 'SELECT * FROM category'; //sql操作语句 就是sql条件 $stm = $pdo->prepare($sql); //prepare() 创建sql语句对象 //$stm ->execute()取出结果 结果为1 则连接取出通道成功。0 为失败 // print_r($stm ->execute()); print_r($stm->fetch(PDO::FETCH_ASSOC)); ?>
点击 "运行实例" 按钮查看在线实例
1、连接数据库 $pdo = new PDO('mysql:host=127.0.0.1;dbname=chenqingxuan', 'root', 'cqx07231950');
为了方便数据库维护(如更改数据库)将数据库内容编译在数据里面。将对应内容拼接在链接里
$db = [
'type'=>'mysql',
'host'=>'127.0.0.1',
'dbname'=>'chenqingxuan',
'username'=>'root',
'password'=>'cqx07231950'
];
$dsn=$db['type'].':host='.$['host'].';dbname='.$db['dbname'];
$pdo = new PDO($dsn, $db['username'], $db['password']);
2、命名sql查询数据
$sql = ' SELECT * FROM category';
3、索引到对应数据
$stm = $pdo->prepare($sql );
4、取出数据
$stm ->execute() ;
$a = $stm->fetch(PDO::FETCH_ASSOC);