I'm trying to echo out 10 numbers from my database in descending order sort of like a Highscores table.
This is my code
$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?>
I'm new to PDO/PHP I didn't get any errors it just doesn't print anything from my table its just blank ;/
You need to fetch the data from the object. I'll provide a link rather than code that will be helpful to you.
It should give you good introduction. It covers your question.
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers#Running_Simple_Select_Statements
you have to fetch the results in a array, and then echo the elements of the array.
$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.";
}
In queries that return large results I wouldn't use $stmt->fetchAll(). I would use fetch in a while loop like this:
$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.";
}
The difference between the first code chunk and the second is that in 1st chunk, we fetch all the results in a array and print them. In the second one tho, we print the data as we retrieve them one by one with PDOStatement::fetch()