查询数据库中相关信息

# 注意:如果用'fetch'代替'fetchAll'则返回的是一维数组,且是第一条结果
# 最简单的方式执行
$dbh = new PDO('mysql:dbname=book_base;host=192.168.1.137', 'root', 'root');
$dbh->exec("set names utf8");
$sql = <<<SQL
SELECT 
  *
FROM
  `user`
WHERE
  `user`.id = 1
SQL;
$result = $dbh->fetchAll($sql);
unset($dbh);
# 查询1条结果
$result = $dbh->fetch($sql);
unset($dbh);

# 按序绑定参数执行
$dbh = new PDO('mysql:dbname=book_base;host=192.168.1.137', 'root', 'root');
$dbh->exec("set names utf8");
$sql = <<<SQL
SELECT 
  *
FROM
  `user`
WHERE
  `user`.id IN (?,?,?,?,?)
SQL;
$sth = $dbh->prepare($sql);
$sth->bindValue(1, 1);
$sth->bindValue(2, 2);
$sth->bindValue(3, 3);
$sth->bindValue(4, 4);
$sth->bindValue(5, 5);
$sth->execute();
$res = $sth->fetchAll();
unset($sth);
unset($dbh);
# 查询1条结果
$res = $sth->fetch();
unset($sth);
unset($dbh);

# 按key绑定参数执行
$dbh = new PDO('mysql:dbname=book_base;host=192.168.1.137', 'root', 'root');
$dbh->exec("set names utf8");
$sql = <<<SQL
SELECT
  *
FROM
  `user`
WHERE
  `user`.id = :id
SQL;
$id = 10000;
$sth = $dbh->prepare($sql);
$sth->bindParam('id', $id);
$sth->execute();
$res = $sth->fetchAll();
unset($sth);
unset($dbh);
# 查询1条结果
$res = $sth->fetch();
unset($sth);
unset($dbh);
@耿志环 2012-∞ 冀ICP备17033181号, powered by Gitbook修订: 2019-01-11 16:52:19

results matching ""

    No results matching ""