0

我试图从我的数据库中以降序的方式回显 10 个数字,有点像高分表。

这是我的代码

$conn = new PDO("mysql:host=HOST;dbname=NAME", "NAME", "PASSWORD");
$hs = $conn->query("SELECT exp FROM login ORDER BY number DESC LIMIT 10");


<? echo $hs?>

我是 PDO/PHP 的新手,我没有收到任何错误,它只是没有从我的表中打印任何内容,它只是空白;/

4

2 回答 2

1

您必须在数组中获取结果,然后回显数组的元素。

$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() 逐一检索数据时打印数据

于 2013-09-15T12:45:14.967 回答
-1

您需要从对象中获取数据。我将提供一个链接而不是对您有帮助的代码。

它应该给你很好的介绍。它涵盖了你的问题。

http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers#Running_Simple_Select_Statements

于 2013-09-15T12:40:59.970 回答