连接
Code
$dsn = 'sqlite:tools.db';
try {
$dbh = new PDO($dsn);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
$dbh = null;
}
$dsn = 'sqlite:tools.db';
try {
$dbh = new PDO($dsn);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
$dbh = null;
}
不带参数查询(1)
Code
1$sql = "SELECT visitor FROM guestbook ORDER BY id DESC";
2foreach ($dbh->query($sql) as $rs) {
3 echo($rs[0]."<br>\n");# 或者 echo($rs["visitor"]);
4}
1$sql = "SELECT visitor FROM guestbook ORDER BY id DESC";
2foreach ($dbh->query($sql) as $rs) {
3 echo($rs[0]."<br>\n");# 或者 echo($rs["visitor"]);
4}
不带参数查询(2)
Code
1$sth = $dbh->prepare("SELECT visitor FROM guestbook");
2$sth->execute();
3$result = $sth->fetch(PDO::FETCH_ASSOC);
4print_r($result["visitor"]);
5print("\n");
1$sth = $dbh->prepare("SELECT visitor FROM guestbook");
2$sth->execute();
3$result = $sth->fetch(PDO::FETCH_ASSOC);
4print_r($result["visitor"]);
5print("\n");
带参数查询
Code
1$sql = 'SELECT visitor, email
2 FROM guestbook
3 WHERE visitor = :visitor ';
4$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
5$sth->execute(array(':visitor' => 'alex'));
6$result = $sth->fetchAll();
7print_r($result) ;
1$sql = 'SELECT visitor, email
2 FROM guestbook
3 WHERE visitor = :visitor ';
4$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
5$sth->execute(array(':visitor' => 'alex'));
6$result = $sth->fetchAll();
7print_r($result) ;
Code
1$sql = 'SELECT visitor, email
2 FROM guestbook
3 WHERE visitor = ? ';
4$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
5$sth->execute(array( 'alex'));
6$result = $sth->fetchAll();
7print_r($result) ;
1$sql = 'SELECT visitor, email
2 FROM guestbook
3 WHERE visitor = ? ';
4$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
5$sth->execute(array( 'alex'));
6$result = $sth->fetchAll();
7print_r($result) ;
Code
1$visitor='alex';
2$sth = $dbh->prepare('SELECT visitor, email
3 FROM guestbook
4 WHERE visitor = :visitor');
5$sth->bindParam(':visitor', $visitor, PDO::PARAM_STR);
6$sth->execute();
7
8foreach ($sth->fetchAll() as $row)
9{
10 echo($row[0]."<br>\n");
11}
1$visitor='alex';
2$sth = $dbh->prepare('SELECT visitor, email
3 FROM guestbook
4 WHERE visitor = :visitor');
5$sth->bindParam(':visitor', $visitor, PDO::PARAM_STR);
6$sth->execute();
7
8foreach ($sth->fetchAll() as $row)
9{
10 echo($row[0]."<br>\n");
11}