回声使用pdo的mysql数据库的最后10个结果

时间:2013-12-30 04:50:19

标签: php mysql database pdo

我正在尝试使用pdo回显数据库中的最后10个项目。但是我一直在查询失败。但是,当我在最底部执行代码片段时,我只能得到数据库中的最后一项。

$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.";
}

但是当我在下面这样做时,它可以工作,但只打印出最后一项

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

2 个答案:

答案 0 :(得分:1)

您需要删除prepare语句。并直接在查询函数中运行查询。

    $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.";
}

此代码正常运作。

文档链接:http://www.php.net/pdo.query

使用prepare你必须使用execute方法。

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

答案 1 :(得分:0)

这是经过测试的代码。

$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>';
}

或者你可以这样做

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