<?php
$db = array(
'dsn' => 'mysql:host=localhost;dbname=test;port=3306;charset=utf8',
'host' => 'localhost',
'port' => '3306',
'dbname' => 'test',
'username' => 'root',
'password' => '123456',
'charset' => 'utf8',
);
//连接
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //默认是PDO::ERRMODE_SILENT, 0, (忽略错误模式)
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // 默认是PDO::FETCH_BOTH, 4
);
try{
$pdo = new PDO($db['dsn'], $db['username'], $db['password'], $options);
}catch(PDOException $e){
die('数据库连接失败:' . $e->getMessage());
}
//或者更通用的设置属性方式:
//$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //设置异常处理方式
//$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); //设置默认关联索引遍历
echo '<pre/>';
//1 查询
//1)使用query
$stmt = $pdo->query('select * from user limit 2'); //返回一个PDOStatement对象
//$row = $stmt->fetch(); //从结果集中获取下一行,用于while循环
$rows = $stmt->fetchAll(); //获取所有
$row_count = $stmt->rowCount(); //记录数,2
print_r($rows);
echo '<br>';
$db = array(
'dsn' => 'mysql:host=localhost;dbname=test;port=3306;charset=utf8',
'host' => 'localhost',
'port' => '3306',
'dbname' => 'test',
'username' => 'root',
'password' => '123456',
'charset' => 'utf8',
);
//连接
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //默认是PDO::ERRMODE_SILENT, 0, (忽略错误模式)
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // 默认是PDO::FETCH_BOTH, 4
);
try{
$pdo = new PDO($db['dsn'], $db['username'], $db['password'], $options);
}catch(PDOException $e){
die('数据库连接失败:' . $e->getMessage());
}
//或者更通用的设置属性方式:
//$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //设置异常处理方式
//$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); //设置默认关联索引遍历
echo '<pre/>';
//1 查询
//1)使用query
$stmt = $pdo->query('select * from user limit 2'); //返回一个PDOStatement对象
//$row = $stmt->fetch(); //从结果集中获取下一行,用于while循环
$rows = $stmt->fetchAll(); //获取所有
$row_count = $stmt->rowCount(); //记录数,2
print_r($rows);
echo '<br>';