php - Getting newest newspost database

611

I'm trying to get the newest post from my Database. If I run the following code I get the following message:

"Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'TABLE newsposts ORDER BY newsposts.post_id DESC ' at line 2"

<?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;


                ";
            }
        ?>
193

Answer

Solution:

get rid of "TABLE" in your SQL statement as theFROM clause assumes a Table.

168

Answer

Solution:

First off, MySQL_* functions are deprecated and you should be using MySQLi or PDO_MySQL

Using PDO, grabbing the latest post is simple:

<?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...
}
873

Answer

Solution:

Your query should be:

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

People are also looking for solutions to the problem: php - Date and Time pickers to Timestamp field

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.