SolidCloudinc
SolidCloudinc

Reputation: 321

Echo last 10 results of mysql database using pdo

I'm trying to echo the last 10 items in my database with pdo. However I keep getting Query failed. However when I do the code snippet at the very bottom I can get just the very last item in my database.

$db2 = new PDO('mysql:host='. $host .';dbname='.$db_name_uroll, $db_username, $db_password);

$statement2 = $db2->prepare("select * from `{$user}` ORDER BY bet_id DESC LIMIT 2");    


if ($stmt = $db2->query($statement2)) //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($row2 = $stmt->fetch(PDO::FETCH_ASSOC)) //This loop will keep going for as many rows as the PDOStatement returns.
    {
        echo $row2['roll'] . "<br />";
    }
}
else
{
    //If PDO::Query returned false, then something is wrong with our query. Or connection or whatever.
     echo "Query failed.";
}

But when I do this below it works, but only prints out the very last item

$row2 = $statement2->fetch();
echo $row2[roll];

Upvotes: 0

Views: 790

Answers (2)

user2727841
user2727841

Reputation: 725

this is tested code.

$dbhost = "localhost";
$dbname = "pdo";
$dbuser = "root";

$con = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser);
echo $select = "SELECT * FROM books ORDER BY id DESC LIMIT 10";
$query = $con->prepare($select);
$query->execute();
$query->setFetchMode(PDO::FETCH_BOTH);
while($row = $query->fetch()) {
    echo '<pre>';print_r($row);echo '</pre>';
}

or you can do like this

if($query->execute()) {
   $query->setFetchMode(PDO::FETCH_BOTH);
   while($row = $query->fetch()) {
       echo '<pre>';print_r($row);echo '</pre>';
   }
} else {
    echo "Query failed";
}

Upvotes: 0

M I
M I

Reputation: 3682

You need to remove prepare statement. and run query directly inside query function.

    $db2 = new PDO('mysql:host='. $host .';dbname='.$db_name_uroll, $db_username, $db_password);

//Remove $db2 prepare
$statement2 = "select * from `{$user}` ORDER BY bet_id DESC LIMIT 2";    


if ($stmt = $db2->query($statement2)) //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($row2 = $stmt->fetch(PDO::FETCH_ASSOC)) //This loop will keep going for as many rows as the PDOStatement returns.
    {
        echo $row2['roll'] . "<br />";
    }
}
else
{
    //If PDO::Query returned false, then something is wrong with our query. Or connection or whatever.
     echo "Query failed.";
}

This code is working.

Docs link: http://www.php.net/pdo.query

Using prepare you have to use execute method.

http://www.php.net/manual/en/pdo.prepare.php

Upvotes: 1

Related Questions