Okay, so this little tutorial could be implemented into a blog, or forum script, so here goes:
You will need a table set up called CMS, and rows within that called Title, Body, Name & ID (ID should be a primary key and auto increment)
Okay so first we need to create a file called getposts.php
First of all open your PHP tags and define the function name and parameters
First we need to create a query and an IF statement that checks if the post existsCode:<?php
//Defines the function name
function get_posts () {
If the number returned was a 1, it means there is a post in the database available to show. We must now tell PHP how to display it, and what error message to display if the post did not existCode://Select everything from the the table
$sql = "SELECT * FROM cms ORDER BY id DESC";
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res) != 0):
//Reads the $res variable
while($row = mysql_fetch_assoc($res)) {
Okay so there you have it, we have created the function in order to get the posts, but we now need to declare the function and get the posts,Code://Makes posts titles into links
echo htmlspecialchars((stripslashes($row['title'])));
echo nl2br(stripslashes(($row['body'])));
echo'<br /><h6>Posted By: ' . stripslashes(($row['name'])) . '</h6>';
}
//If there were no rows, and the post didnt exist, then display an error message
else:
echo '<p>We cant seem to find that post!</p>';
endif;
//Ends the function
}
?>
Just include this file on the page you want the posts to show up on and there you have it!Code:<?php
get_posts();
?>
(Don't forget to include your connection info)
Last edited by Bioshox; 03-04-2010 at 01:24 PM. Reason: replace [code] tags with [php] tags
This is a good tut esp for those wanting to make there own forum / blog script. + rep
Just thinking. why the $id? you don't use it? this code will show ALL posts in the table, not just one, as I understood seemed to be the meaning from the comments. Additionally, the code is plottered with loads of usually unnecessary stripslashes(), and this means that this is extremely dependent on how your data was stored to the database, on where there is nothing shown...
__________________________________________
I study Information Systems at Karlstad University when I'm not on CodeCall
I'd also be happier if I saw a good indentation and whitespace usage so the code is more readable :-)
__________________________________________
I study Information Systems at Karlstad University when I'm not on CodeCall
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks