$pdo->prepare($sql)
$stmt->execute()
$stmt->fetch()
<?php
header("content-type:text/html;charset=utf-8");
try {
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$sql = 'select * from user where username="king11"';
//prepare($sql) 准备SQL语句
$stmt = $pdo->prepare($sql);
var_dump($stmt);
/*
* object(PDOStatement)[2]
* public 'queryString' => string 'select * from user where username="king11"' (length=42)
*/
//execute() 执行预处理语句
$res = $stmt->execute();
var_dump($res);//boolean true
//fetch() 得到结果集中的一条记录
$row = $stmt->fetch();
var_dump($row);
/**
* array
* 'id' => string '40' (length=2)
* 0 => string '40' (length=2)
* 'username' => string 'king11' (length=6)
* 1 => string 'king11' (length=6)
* 'password' => string 'e02cc1e4e6d565fe7df86ce90834f150' (length=32)
* 2 => string 'e02cc1e4e6d565fe7df86ce90834f150' (length=32)
* 'email' => string 'imooc@qq.com' (length=12)
* 3 => string 'imooc@qq.com' (length=12)
*/
} catch (PDOException $e) {
echo $e->getMessage();
}
?>
<?php
header("content-type:text/html;charset=utf-8");
try {
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$sql = 'select * from user ';
$stmt = $pdo->prepare($sql);
$res = $stmt->execute();
if ($res) {
while ($row = $stmt->fetch()) {
echo "用户名:" . $row['username'];
echo "<hr/>";
}
}
} catch (PDOException $e) {
echo $e->getMessage();
}
?>
$stmt->fetchAll()
$rows = $stmt->fetchAll();
var_dump($rows);
$stmt->fetch(PDO::FETCH_ASSOC)
if ($res) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "用户名:" . $row['username'];
echo "<hr/>";
}
}
PDO::FETCH_BOTH
while ($row = $stmt->fetch(PDO::FETCH_BOTH))
PDO::FETCH_OBJ
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
PDO::FETCH_ASSOC
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->setFetchMode()
$stmt->setFetchMode(PDO::FETCH_ASSOC);
var_dump($stmt->fetchAll());