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;
";
}
?>
get rid of "TABLE" in your SQL statement as the FROM
clause assumes a Table.
Your query should be:
SELECT newsposts.post_id, newsposts.post
FROM newsposts
ORDER BY newsposts.post_id DESC
LIMIT 1
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...
}