获取最新的newspost数据库

时间:2013-11-06 15:05:13

标签: php mysql

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

“无效的查询:您的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;


                ";
            }
        ?>

3 个答案:

答案 0 :(得分:6)

在SQL语句中删除“TABLE”,因为FROM子句假定为表。

答案 1 :(得分: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...
}

答案 2 :(得分:0)

您的查询应该是:

SELECT newsposts.post_id, newsposts.post 
FROM newsposts 
ORDER BY newsposts.post_id DESC 
LIMIT 1