Simple blog post function
How would I create a simple blog posting function in PHP? I have a mySQL database with the following...
Table bloggers: i开发者_JAVA技巧d, name
Table posts: blogger id, post, timestamp
In plain English I want to display all posts with the blogger's name (by matching the id with blogger id) and a timestamp, and the posts ordered by the timestamp to have the most recent ones first.
My current endeavours of selecting each one nested within the other isn't working and I think I need to rethink the whole approach.
I'd suggest you read up on the basics of SQL as this seems pretty straightforward:
SELECT
b.name, p.post, p.timestamp
FROM
posts p
INNER JOIN
bloggers b
ON
p.blogger_id = b.id
WHERE
b.blogger_id = :id
ORDER BY
p.timestamp DESC
Note that the :id
part above is for use in a prepared statement, described below.
As for the PHP function, you should use PDO for this.
try sql:
select * from bloggers A, posts B WHERE A.bloggerid = B.bloggerid
I may not quite understand how you're organizing things but...
Assuming you can get the author's id by selecting the bloggers table and getting the id you want you could do something like this:
$result = mysql_query("SELECT * FROM posts WHERE blogger_id='" . $author_id . "' ORDER BY timestamp DESC") or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
echo '<div class="post"><div class="time">' . $row['timestamp'] . '</div><div class="content">'. $row['post'] .'</div></div>';
}
精彩评论