0

我正在尝试从我的数据库中获取最新帖子。如果我运行以下代码,我会收到以下消息:

“无效查询:您的 SQL 语法有错误;请检查与您的 MySQL 服务器版本相对应的手册,以在第 2 行的 'TABLE newsposts ORDER BY newsposts.post_id DESC' 附近使用正确的语法”

<?php
            $getPosts = mysql_query("SELECT newsposts.post_id, newsposts.post 
                     FROM TABLE newsposts 
                 ORDER BY newsposts.post_id DESC 
                    LIMIT 1") or die('Invalid query: ' . mysql_error());
            while($getPosts_Array = mysql_fetch_array($getPosts)){

                $post_id = $getPosts_Array['post_id'];
                $post = $getPosts_Array['post'];

                echo "  
                            $post;


                ";
            }
        ?>
4

3 回答 3

6

在您的 SQL 语句中去掉“TABLE”,因为该FROM子句假定为一个表。

于 2013-11-06T15:09:07.220 回答
2

首先,不推荐使用 MySQL_* 函数,您应该使用MySQLiPDO_MySQL

使用 PDO,获取最新帖子很简单:

<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$stmt = $db->query('SELECT post_id, post FROM newsposts ORDER BY post_id DESC LIMIT 1');
$stmt->execute();

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo 'Post #'.$row['post_id'].': '.$row['post']; //etc...
}
于 2013-11-06T15:18:57.363 回答
0

您的查询应该是:

SELECT newsposts.post_id, newsposts.post 
FROM newsposts 
ORDER BY newsposts.post_id DESC 
LIMIT 1
于 2013-11-06T15:09:42.070 回答