advertisement

The script is all based on PHP with a bit of MySQL (to store the comments and news posts) and also we will be using some javascript for the comments system.

Well enough jibber-jabber, let’s get started.

First off we are going to have to create our database. I am using cPanel so I can create my databases from there. I am going to call my database news with a username of script and a password of tutorialcode.

Whenever you create a database in cPanel your database and username are given a prefix. This prefix is pre-determined by what your username is to login to cPanel. So for me this is tutorial. (IE : My database is now tutorial_news and my username is tutorial_script)

Now we need to create the tables in our database to hold the news posts and the comments.

Let’s start off by creating out news posts table.
[mysql]
CREATE TABLE news_posts (
id INT(11) NOT NULL AUTO_INCREMENT,
title VARCHAR(70) NOT NULL,
author VARCHAR(50) NOT NULL,
post TEXT NOT NULL,
date DATETIME NOT NULL,
PRIMARY KEY (id)
);
[/mysql]
This will create our news_posts table in which our news posts will be stored in, this just creates a table that has 5 rows, the first row will be our news posts ID. This number will auto increment (Meaning it will go up automatically) and this number will never be duplicated for that row. Then I have a title row, this will store the title of our news posts, then I have an author row, this will store the author of the news posts, then we have our post row. This will store the actual text for our news post. Then I have a row title date. This will be automatically inserted at the exact moment that it is inserted into the table. Then we create a PRIMARY KEY for our ID row, this is to guarantee that the number entered in the ID row is always unique, since all of our news posts are unique.

Now let’s create our comments table. Since we will only want to display each comment that applys to the news posts they were posted on this table will require 2 id fields, 1 id field will be the actual ID of the comment, and the other ID field (we will call it nid) will have the number of the news post that the comment is posted for. So when we go to retrieve our comments, we can retrieve the right comments for that news post.
[mysql]
CREATE TABLE comments (
id INT(11) NOT NULL AUTO_INCREMENT,
nid INT(11) NOT NULL,
title VARCHAR(70) NOT NULL,
author VARCHAR(50) NOT NULL,
comment TEXT NOT NULL,
date DATETIME NOT NULL,
PRIMARY KEY (id)
);
[/mysql]
This table is pretty much the exact same as our news_posts table with the exception that I have added a nid row (which I explain above) and also instead of a row called post it is now named comment.

Now let’s get started with the actual PHP code of this project. First we are going to start off by creating a file called mysql_connect.php

<?php
DEFINE ('DB_USER', 'tutorial_script'); // Insert your database username into the quotes.
DEFINE ('DB_PASSWORD', 'tutorialcode'); // Insert your database password into the quotes.
DEFINE ('DB_HOST', 'localhost'); // This will most likely stay the same.
DEFINE ('DB_NAME', 'tutorial_news'); Insert your actual database name in the quotes.

$dbc = @mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL: ' . mysql_error());
@mysql_select_db (DB_NAME) OR die('Could not select the database: ' . mysql_error() );
?>

This part of our script actually connects to our database. It first defines 4 variables. Each variable is a part of our database (Host, username, database and password). So for this part of the tutorial insert your database specifications. I have left comments in the code to help better explain this. As you can see I input my database specifications for the database that I created earlier into the quotes.

Now save this file as mysql_connect.php and upload it to your webserver. If you now visit it on your webserver (ex : www.yourwebsite.com/mysql_connect.php) you will see a blank page, this means it worked. If you see any errors then that means the connection to the database did NOT work. This means you must have input your database specifications in wrong. Once you finally get a blank white page you may continue.

Next we are going to create the admin part of our script. So we are going to create a file called addnews.php.

For this script I will not be including any login authorization or admin authorization to add news, delete news or edit news. If you are to use this script on your own website it is recommended that you place the script in an area that requires login from an admin.

<?php
if (isset($_POST['submitted'])) {
include ('mysql_connect.php');
if (empty($_POST['title'])) {
echo '<p><font color="red">You need to enter a title.</font></p>';
} else {
$title = $_POST['title'];
}

if (empty($_POST['name'])) {
echo '<p><font color="red">You need to enter a name.</font></p>';
} else {
$name = $_POST['name'];
}

if (empty($_POST['message'])) {
echo '<p><font color="red">You need to enter a message.</font></p>';
} else {
$message = $_POST['message'];
}

if ($title && $name && $message) {
$query = "INSERT INTO news_posts (title, author, post, date) VALUES ('$title', '$name', '$message', NOW())";
$result = @mysql_query($query);

if ($result) {
echo '<p><font color="red">News was added!</font></p>';
} else {
echo '<font color="red"><p>News could not be added! Please try again.</p></font>';
}
} else {
echo '<p><font color="red">Please fill in the appropriate information</font></p>';
}
}
?>

<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<p><b>News Title :</b><br />
<input type="input" name="title" size="25" maxlength="60" value="<?php if(isset($_POST['title'])) echo $_POST['title']; ?>" /></p>

<p><b>Name :</b><br />
<input type="input" name="name" size="15" maxlength="35" value="<?php if(isset($_POST['name'])) echo $_POST['name']; ?>" /></p>

<p><b>Message :</b><br />

<textarea rows="7" cols="55" name="message"><?php if(isset($_POST['message'])) echo $_POST['message']; ?></textarea></p>

<p><input type="submit" name="submit" value="Add News" /></p>
<input type="hidden" name="submitted" value="TRUE" /></p>
</form>

Now lets break this file down into pieces for better explanation.

<?php
if (isset($_POST['submitted'])) {
include ('mysql_connect.php');
if (empty($_POST['title'])) {
echo '<p><font color="red">You need to enter a title.</font></p>';
} else {
$title = escape_data($_POST['title']);
}

Alright, at first glance this piece of code may seem daunting, but fear not it is quite easy. All we do here is first start off our PHP document with <?php. Then we use a function called isset(). What this function does is check if a form is submitted. So here we check if $_POST[‘submitted’] was submitted using the isset() function. If it was submitted then we continue on.

Then we include our mysql_connect.php file, this is so now we have an active connection to our database so we can insert our news posts.

Then we use a new function called empty(). This checks to see if a form field was entered as empty or not. In this script we check if the field $_POST[‘title’] was empty or not. In this case if the field is empty then we continue onto the next part where we display an error telling the user they left the field empty, if the field was NOT empty then we come to the part of the code where we create our variable $title and give it the value of our field by using $_POST[‘title’].

Then we have 2 more form validations after this one that are exactly the same. (Except for the field name of course, so just replace that if you need better explanation with the appropriate form field name, and also the variable name.)

if ($title && $name && $message) {
$query = "INSERT INTO news (title, name, message, date) VALUES ('$title', '$name', '$message', NOW())";
$result = @mysql_query($query);

More code explanations! This part of our script is where our query is created, this is the query we will be using to insert our news posts into our database. We first create a variable called $query. We will then give it the value of our actual query. So we use an INSERT query and insert the appropriate values into the appropriate places.

I use a NOW() function for our date row, this will insert our date at the exact moment of posting. Then we create a variable called $result. This is where we execute our query using the mysql_query() function. I add an @ sign before the function so that if any errors happen it will NOT display the default ugly PHP errors.

if ($result) {
echo '<p><font color="red">News was added!</font></p>';
} else {
echo '<font color="red"><p>News could not be added! Please try again.</p></font>';
}
} else {
echo '<p><font color="red">Please fill in the appropriate information</font></p>';
}
}
?>

The final part of our PHP code for this file is where we check if our variable $result is TRUE or FALSE. If it is TRUE (Which means the query worked), we display a message to the user saying it worked. If it did NOT worked then we display a message telling the user. Then we finish our PHP document with the ?> tag.

<form name="addnews" action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<p><b>News Title :</b><br />
<input type="input" name="title" size="25" maxlength="60" value="<?php if(isset($_POST['title'])) echo $_POST['title']; ?>" /></p>

<p><b>Name :</b><br />
<input type="input" name="name" size="15" maxlength="35" value="<?php if(isset($_POST['name'])) echo $_POST['name']; ?>" /></p>

<p><b>Message :</b><br />

<textarea rows="7" cols="55" name="message"><?php if(isset($_POST['message'])) echo $_POST['message']; ?></textarea></p>

<p><input type="submit" name="submit" value="Add News" /></p>
<input type="hidden" name="submitted" value="TRUE" /></p>
</form>

Then we create our HTML form, I use stick forms so the user doesn’t lose the information they have input. Learn more about sticky forms by reading our tutorial.

Then I just create basic input fields, and a text area for our news post to be entered in.

Now we will create a page where we can view the news posts that we enter. I am going to call this file news.php

<html>
<head>
<script type="text/javascript">
function openComments(url)
{
comments = window.open(url, "Comment", "menubar=0,resizable=0,width=380,height=480")
comments.focus()
}
</script>
</head>
<body>
<?php
include ('mysql_connect.php');
$query = "SELECT id, title, author, post, DATE_FORMAT(date, '%M %d, %Y') as sd FROM news_posts";
$result = @mysql_query($query);

if ($result) {
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url = 'comments.php?id='.$row['id'];
echo '<p><b>'.$row['title'].'</b><br />
'.$row['sd'].'<br />
Posted by : <b>'.$row['author'].'</b><br />
'.$row['post'].'<br />
<a href="javascript:openComments(\''.$url.'\')">Add new comment or view posted comments</a></p>';
}
} else {
echo 'There are no news posts to display';
}
?>
</body>
</html>

This is just a little bit of code (Thats all we need to display our news )

I will just explain it all here, first we start off by creating our HTML document, then in the head of our document we create a new javascript function by using the <script> tag. This is just a simple function to open a new window with a url that we input.

So all we are doing is creating our function, I am calling it openComments. Then we give it a new parameter called url. This where we input the URL of our comment for our specific news post. Then we just use the new.window() function to open the function with our URL. If this all seems fuzzy to you take a look at our tutorial on Javascript functions.

Then we start our PHP document. We include our mysql_connect.php since we will need our database to retrieve our news posts. Next we get right down to it and create our query, we select everything from our news_posts table, we use the DATE_FORMAT MySQL function to format our date to our liking. Then we execute our query and set the result to the variable of $result. Then we check if our query went off without a hitch, next we need to display our news posts. So I have used a while() loop to do this.

I am creating a new array using our result from our database and calling this array $row, I am defining it as MYSQL_ASSOC. This means our array wont be numbers for the rows, it will be the actual row names. If you wanted to use numbers you can use MYSQL_NUM instead. Then we define the URL that we are going to be using for our javascript function, after that we just echo out the information for our news post, the title, author, date it was posted and the actual news post its self. Then we create a link that actually uses our javascript function. We put in our $url variable for the url parameter we defined in our javascript function earlier. Then we just need to make an } else { statement if there are no news posts to display and finish off our PHP document and thats it!

Alright, only 3 more small files to create and your done! Our next file that we are creating will be the file where we view and add new comments to our page. I am calling this file comments.php.

<?php
include ('mysql_connect.php');

if (isset($_GET['id'])) {
$id = $_GET['id'];
} else {
echo 'Please select a news post to view the comments.';
exit();
}
$query = "SELECT * FROM comments WHERE nid = $id";
$result = @mysql_query($query);

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<b>'.$row['title'].'</b>
<b>Author : </b>'.$row['author'].'<br />
<b>Comment : </b>'.$row['comment'].'<br />
<hr width="80%" />';
}

if (isset($_POST['submitted'])) {

$errors = array();
if (empty($_POST['title'])) {
$errors[] = '<font color="red">Please enter in a title.</font>';
} else {
$title = $_POST['title'];
}

if (empty($_POST['author'])) {
$errors[] = '<font color="red">Please enter in your name.</font>';
} else {
$author = $_POST['author'];
}

if (empty($_POST['comment'])) {
$errors[] = '<font color="red">Please enter in a comment.</font>';
} else {
$comment = $_POST['comment'];
}

if (empty($errors)) {
$query = "INSERT INTO comments (nid, title, author, comment, date) VALUES ($id, '$title', '$author', '$comment', NOW())";
$result = @mysql_query($query);

if ($result) {
echo '<font color="blue">Your comment was added succesfully!</font>';
} else {
echo '<font color="red">There was an error when submitting your comment, please try again.</font>';
}
} else {
echo '<b>There were a couple of errors -</b><br />';
foreach ($errors as $msg) {
echo " - $msg<br />\n";
}
}
} else {
?>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post" />
<p>Comment Title : <input type="text" name="title" maxlength="70" value="<?php if(isset($_POST['title'])) echo $_POST['author'];?>" /></p>

<p>Your Name : <input type="text" name="author" length="25" maxlength="50" value="<?php if(isset($_POST['author'])) echo $_POST['author'];?>" /></p>

<p>Comment : <textarea columns="6" rows="6" name="comment"><?php if(isset($_POST['comment'])) echo $_POST['comment'];?></textarea></p>

<p><div align="center"><input type="submit" name="submit" value="Submit Comment" /></div></p>
<input type="hidden" name="submitted" value="TRUE" />
</form>
<?php
}
?>
<div align="center"><a href="javascript:window.close()">Close this window</a></div>

This is our code for displaying and adding new comments. First we include our mysql_connect.php file so that we can use our database information. Then we check to see if $_GET[‘id’] was submitted or not, this is what is in our URL. (EX : www.yourwebsite.com/comments.php?id=1). Then we create our query to retrieve any comments from our database.

Then we do some form validation, this is the exact same is in previous files. Except different form fields, then if there are no errors we create our query to insert our data into our table. Then at the end of our script we just create the form that people use to insert there comments. Pretty straight forward eh?

Next we are going to create the file for deleting news posts. But before we do that, we need to create a file to manage our news posts. This will be called news_manage.php.

<?php
include('mysql_connect.php');
$query = "SELECT id, title FROM news_posts";
$result = @mysql_query($query);

if ($result) {
echo '<div align="center">
<table border="0">
<tr>
<td><b>ID</b></td>
<td><b>Title</b></td>
<td><b>Delete</b></td>
<td><b>Edit</b></td>
</tr>';

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<tr>
<td>'.$row['id'].'</td>
<td>'.$row['title'].'</td>
<td><a href="delete_news.php?id='.$row['id'].'">Delete</a></td>
<td><a href="edit_news.php?id='.$row['id'].'">Edit
</tr>';
}
} else {
echo 'Sorry, but we could not retrieve any news item records.';
}
?>

This is just a simple small part of code that retrieves our news posts from our database and displays them in a table with Delete and Edit links beside each one. Save this file as news_manage.php

Now we create our script to delete our news. This will be called delete_news.php.

<?php
if (isset($_GET['id'])) {
include('mysql_connect.php');
if (is_numeric($_GET['id'])) {
$id = $_GET['id'];

$query = "DELETE FROM news_posts WHERE id = $id";
$result = mysql_query($query);

if ($result) {
echo '<h3>Success!</h3><br />
The news item was deleted succesfully.<br /><br />
<b>Options :</b><br />
Delete or Edit another news item : <a href="news_manage.php">[X]</a><br />
Add a new news item : <a href="addnews.php">[X]</a><br />';
} else {
echo 'We are sorry to inform you but the news item you chose to delete could not be deleted. Please feel free to try again';
}
} else {
echo 'Invalid news item, please choose a news item.';
}
} else {
echo 'Before visiting this page please choose a news item to delete first!';
}
?>

This is just another small piece of code that retrieves the specific news post from the database that corresponds to the ID that was passed through the URL. If it is found then it deletes it from the database and displays a message saying if it worked our not. Now we need a file to edit our news posts, this is pretty much the exact same as our add news post except the values of the form fields is already put in. I am going to call this file edit_news.php.

<?php
include('mysql_connect.php');
if ((isset($_GET['id'])) && (is_numeric($_GET['id'])) ) {
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) {
$id = $_POST['id'];
} else {
echo 'Please choose a news post to edit.';
exit();
}

if (isset($_POST['submitted'])) {
$errors = array();

if (empty($_POST['title'])) {
$errors[] = 'You forgot to enter a title.';
} else {
$title = $_POST['title'];

}

if (empty($_POST['name'])) {
$errors[] = 'You forgot to enter an author.';
} else {
$name = $_POST['name'];
}

if (empty($_POST['message'])) {
$errors[] = 'You forgot to enter a message';
} else {
$message = $_POST['message'];
}

if (empty($errors)) {
$query = "UPDATE news_posts SET title='$title', author='$name', post='$message' WHERE id=$id";
$result = mysql_query($query);

if ($result) {
echo "News Post Has Been Updated!";
} else {
echo "News post could not be updated.";
}
} else {
echo 'News post could not be updated for the following reasons -<br />';
foreach ($errors as $msg) {
echo " - $msg<br />\n";
}
}
} else {
$query = "SELECT title, author, post, id FROM news_posts WHERE id=$id";
$result = mysql_query($query);
$num = mysql_num_rows($result);
$row = mysql_fetch_array ($result, MYSQL_NUM);

$title = $row['0'];
$name = $row['1'];
$message = $row['2'];

if ($num == 1) {
echo '<h3>Edit News Post</h3>
<form action="?id=edit_news&num='.$id.'" method="post">
<p>News Title : <input type="text" name="title" size="25" maxlength="255" value="'.$title.'" /></p>
<p>Name : <input type="text" name="name" size="15" maxlength="255" value="'.$name.'" /></p>
<p>Message : <br /><textarea rows="5" cols="40" name="message">'.$message.'</textarea></p>
<p><input type="submit" name="submit" value="Submit" /></p>
<input type="hidden" name="submitted" value="TRUE" /></p>
<input type="hidden" name="id" value="'.$id.'" />';
} else {
echo 'News post could not be edited, please try again.';
}
}
?>

This is basically the exact same as our addnews.php script except for the form part. Before we display the form we make a query that selects a news post from the database that corresponds to the id number that we passed through the URL. Then it sets the value=” ” attribute of each of the form fields to the appropriate pieces of information from the data that we extraced from the database.

And that’s it! Phew, that was long! I hope you learned something from this tutorial and plan on using it on your very own website! All the files have been tested and work.

If you have any questions feel free to send us an email using the contact form located on the site.

Thanks
Sean

Extension: Search Form

advertisement