您必须在数组中获取结果,然后回显数组的元素。
$db = new PDO("mysql:host=$db_hostname;dbname=$database", $db_username, $db_password);
$sql = "SELECT exp FROM login ORDER BY number DESC LIMIT 10";
if ($stmt = $db->query($sql)) //PDO::query() returns a PDOStatement on success or false on failure.
{
//If we got a PDOStatement as a return value from PDO::Query() fetch the results and echo.
if($numbers = $stmt->fetchAll(PDO::FETCH_ASSOC)) //This will fetch all results in associative array.
{
//If the array contained data, then echo them.
foreach ($numbers as $num)
{
echo $num['exp'] . "<br />";
}
}
else
{
//If the PDOStatement returned an empty array. Let us know.
echo "No data in the array";
}
}
else
{
//If PDO::Query returned false, then something is wrong with our query. Or connection or whatever.
echo "Query failed.";
}
在返回大结果的查询中,我不会使用 $stmt->fetchAll()。我会在这样的while循环中使用fetch:
$db = new PDO("mysql:host=$db_hostname;dbname=$database", $db_username, $db_password);
$sql = "SELECT exp FROM login ORDER BY number DESC LIMIT 10";
if ($stmt = $db->query($sql)) //PDO::query() returns a PDOStatement on success or false on failure.
{
//If we got a PDOStatement as a return value from PDO::Query() !!!ECHO WHILE FETCHING!!!
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) //This loop will keep going for as many rows as the PDOStatement returns.
{
echo $row['exp'] . "<br />";
}
}
else
{
//If PDO::Query returned false, then something is wrong with our query. Or connection or whatever.
echo "Query failed.";
}
第一个代码块和第二个代码块之间的区别在于,在第一个代码块中,我们将所有结果放在一个数组中并打印出来。在第二个中,我们在使用 PDOStatement::fetch() 逐一检索数据时打印数据