在 mysql 中,我们知道有 mysql_fetch_row()、mysql_fetch_array() 和 mysql_fetch_assoc()。
对于 PDO,有很多类型的 fetch
<?php
// configuration
$dbtype= "mysql";
$dbhost= "localhost";
$dbname= "test";
$dbuser= "root";
$dbpass= "admin";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$sql = "SELECT title FROM books ORDER BY title";
$q = $conn->query($sql);
// fetch
while($r = $q->fetch()){
print_r($r);
}
// result
//Array ( [title] => book_title [0] => book_title )
?>
这是你不必准备声明的时候,如果你必须这样做,你应该按照这个步骤
<?php
// configuration
$dbtype= "mysql";
$dbhost= "localhost";
$dbname= "test";
$dbuser= "root";
$dbpass= "admin";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$title = 'PHP AJAX is Awesome';
// query
$sql = "SELECT * FROM books WHERE title = ?";
$q = $conn->prepare($sql);
$q->execute(array($title));
$q->setFetchMode(PDO::FETCH_BOTH);
// fetch
while($r = $q->fetch()){
print_r($r);
}
?>
如果您使用通配符会更好吗?对于属性(因为它类似于 ORM 系统)
例如,在您的情况下,您应该这样做
$query = "SELECT COUNT(*) FROM table WHERE home_team=? AND home_score > ?";
$stmt = $db->prepare($query);
$stmt->execute(array($team,$HScore));
$stmt->setFetchMode(PDO::FETCH_BOTH);
$numbers = $stmt->fetch();