我正在尝试从数据库中按下降顺序回显出10个数字,就像Highscores表一样。
这是我的代码
$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的新手我没有得到任何错误它只是没有从我的表中打印任何东西它只是空白; /
答案 0 :(得分: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-&gt; 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()
逐个检索它们答案 1 :(得分:-1)
您需要从对象中获取数据。我将提供一个链接,而不是代码,对您有所帮助。
它应该给你很好的介绍。它涵盖了你的问题。
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers#Running_Simple_Select_Statements