News Articles (SQL/PHP Based)

By Jonesy44 on Mar 31, 2008

UPDATED: Edit/Delete functions added

This is a simple, (no graphics) webpage for displaying news from an SQL table with an add feature.

Ok, so the first thing you need to do, is create a new table within your database. either use phpMyAdmin, running this SQL code.

CREATE TABLE `news` (
`id` INT( 255 ) NOT NULL AUTO_INCREMENT ,
`title` VARCHAR( 255 ) NOT NULL ,
`article` TEXT NOT NULL ,
`updated` VARCHAR( 255 ) NOT NULL ,
PRIMARY KEY ( `id` )
) TYPE = MYISAM ;

or put it in a webpage, and view it (within a mysql_query). Running the SQL code through phpMyAdmin is the suggested way.

Secondly, create a new webpage, for example:

/home/www/www.website.com/news.php

Then, paste the code from the snippet in.

The following code needs to be edited to your website.

mysql_connect('host', 'login_to_sql', 'password_to_sql');

host = your mysql host. if you are using phpMyAdmin, you should get a message such as:

Welcome to phpMyAdmin
MySQL 4.1.18-log running on fdb1.runhosting.com as your_username@xx.your.ip.xx
The part you want from that is fdb1.runhosting.com

login_to_sql = your username, before the @ symbol in the previous quote.

password_to_sql = the password you used to get to your phpMyAdmin (or other SQL prog.)

Next, set the database_name as your databases name.

[b]Now, you have your db set up and webpage running. You're pretty much ready to roll. Remember this web requires a log in (password is changed within the script:

      if ($_POST["pass"] == "jonesy") {

Just change "jonesy" to "xx_yourpass".[/b]

[b]A working version of this script can be found at :
http://wfs.myartsonline.com/news
Password = jonesy

I'll leave it up for a week or two as an example.
If you have any questions, drop me a PM or leave a comment

<?php

session_start();
mysql_connect('host', 'login_to_sql', 'password_to_sql');
mysql_select_db('database_name');
$day = gmdate(j);
$month = gmdate(F);
$year = gmdate(Y);
$date = $day. " " .$month. " " .$year;

echo "<title>My News Page</title>
      <h1><a href=?>My News Page</a></h1>";

if ($_GET["admin"] == "add") {
  if (!isset($_SESSION["admin"])) {
    echo "<a href=?admin=login>You are not logged in as an admin</a>";
    exit();
  }
  else {
    if ($_POST) {
      if ($_POST["title"] == "") {
        echo "No title entered<br>";
        exit();
      }
      if ($_POST["article"] == "") {
        echo "No article entered";
        exit();
      }
      else {
        mysql_query("INSERT INTO `news` ( `id` , `title` , `article` , `updated` ) VALUES ('', '" .$_POST["title"]. "', '" .$_POST["article"]. "', '" .$date. "')");
        echo "Article Posted<hr>
              <b>Title:</b> " .$_POST["title"]. "<br>
              <b>Article:</b> " .$_POST["article"]. "";
      }
    }
    else {
      echo "<form action=?admin=add method=post>
            <table width=100% border=1>
            <tr><td>Title:</td><td><input type=text name=title size=100></td></tr>
            <tr><td>Article:</td><td><textarea name=article rows=10 cols=100></textarea></td></tr>
            <tr><td colspan=2><input type=submit value=\"Add Article\"></td></tr></form>";
    }
  }
}
if ($_GET["admin"] == "del" && $_GET["id"]) {
  if (!isset($_SESSION["admin"])) {
    echo "<a href=?admin=login>You are not logged in as an admin</a>";
    exit();
  }
  else {
    mysql_query("DELETE FROM `news` WHERE `id` = '" .$_GET["id"]. "'");
    echo "<a href=?>Your article has been deleted</a>";
  }
}
if ($_GET["admin"] == "edit" && $_GET["id"]) {
  if (!isset($_SESSION["admin"])) {
    echo "<a href=?admin=login>You are not logged in as an admin</a>";
    exit();
  }
  if ($_POST) {
    mysql_query("UPDATE `news` SET `title` = '" .$_POST["title"]. "', `article` = '" .$_POST["article"]. "', `updated` = '" .$date. "' WHERE `id` = '" .$_GET["id"]. "'");
    echo "<a href=?>Your article has been edited</a>";
  }
  else {
    $sql = mysql_query("SELECT * FROM `news` WHERE `id` = '" .$_GET["id"]. "' LIMIT 0, 1");
    $news = mysql_fetch_array($sql);
    echo "<form action=?admin=edit&id=" .$_GET["id"]. " method=post>
          <table width=100% border=1>
          <tr><td>Title:</td><td><input type=text name=title size=100 value='" .$news["title"]. "'></td></tr>
          <tr><td>Article:</td><td><textarea name=article rows=10 cols=100>" .$news["article"]. "</textarea></td></tr>
          <tr><td colspan=2><input type=submit value=\"Edit Article\"></td></tr></form>";
  }
}
if ($_GET["admin"] == "login") {
  if (isset($_SESSION["admin"])) {
    echo "You are logged in<br>
          <a href=?admin=logout>Logout Here</a>";
  }
  else {
    if ($_POST["pass"]) {
      if ($_POST["pass"] == "jonesy") {
        echo "<a href=?>You are now logged in</a>";
        $_SESSION["admin"] = 1;
      }
      else {
        echo "<a href=?admin=login>Incorrect Password</a>";
      }
    }
    else {
      echo "<form action=?admin=login method=post>
            <input type=hidden name=admin value=login>
            <input type=password name=pass><br>
            <input type=submit value=Login></form>";
    }
  }
}
if ($_GET["admin"] == "logout") {
  session_destroy();
  echo "<a href=?>You are now logged out</a>";
}
if ($_GET["admin"]) {
  exit();
}

else {
  $sql = mysql_query("SELECT * FROM `news` ORDER BY `id` DESC LIMIT 0, 10");
  echo "<i>Displaying the last 10 new articles</i><hr>";
  while ($news = mysql_fetch_array($sql)) {
    echo "<h3>[" .$news["id"]. "] " .$news["title"]. "<i> - Updated: " .$news["updated"]. "</i></h3>";
    echo $news["article"];
    if (isset($_SESSION["admin"])) {
      echo "<br><a href=?admin=edit&id=" .$news["id"]. ">Edit</a> | <a href=?admin=del&id=" .$news["id"]. ">Delete</a>";
    }
    echo "<hr>";
  }
  if (isset($_SESSION["admin"])) {
    echo "<a href=?admin=add>Add news article</a> | <a href=?admin=logout>Logout</a>";
  }
  else {
    echo "<a href=?admin=login>Login</a>";
  }
}

?>

Comments

Sign in to comment.
sangkilat   -  May 21, 2010

helpfull for me, thx man,...

 Respond  
Jonesy44   -  Jan 06, 2009

This worked fine for me when i was testing, so all i can guess is that your mysql login isnt correct like hawkee said.

 Respond  
Hawkee   -  Jan 06, 2009

axelwai, seems like you've got a problem with your mysql_connect credentials. Make sure you've got the proper login, password and database name. Could also modify the code to set $sql = mysql_connect(...); so you've got a reference to the mySQL handler that you can pass to mysql_fetch_array.

 Respond  
axelwai   -  Jan 06, 2009

Somewhy mysql_fetch_array($sql) makes me problems.
Warning: mysql_fetch_array():
supplied argument is not a valid MySQL result resource in .\news.php on line 65
it said line 106 too

 Respond  
Jonesy44   -  Apr 02, 2008

Thanks for the links Hawkee, i\'ve read through them and updated my current website, haha i just realised how vulnerable it actually was.

Security on this script is not necessary as it\'s designed to be simple, when i get a chance, i\'ll add the extra sanitizing :)

 Respond  
Hawkee   -  Apr 01, 2008

This code is vulnerable to SQL Injection. You should always sanitize your $_GET and $_POST variables before using them in a query with mysql_real_escape_string(). Check this page for information on preventing an injection attack with PHP.

 Respond  
guest598594   -  Apr 01, 2008

It\'s great that you added the edit/delete functions. I posted new news on the sample page :o

 Respond  
Jonesy44   -  Apr 01, 2008

[i][b][u]BUMP

UPDATED: Edit/Delete functions added[/u][/b][/i]

 Respond  
Jonesy44   -  Apr 01, 2008

THanks for the comments EL, Hawkee, mountaindew.
Like i said, this is a very basic script. but shows a small amount of potential of PHP/SQL and how it can be used.

I think my methods in PHP/SQL are slightly elongated cos i dont know much of it xP

 Respond  
EL   -  Mar 31, 2008

Umm i d love to but i dunno how to go about all that sadly sound awesome tho im on teh comp litterly 20+ hourse outta the day workin on my chat sie an codes wouldnt mind doin other things with my time sadly mIRC does get boring lol if you have some suggestion on gettin started liek \'\'PHP for Dumb asses\'\' it be cool if not thats cool theres always google =\

 Respond  
guest598594   -  Mar 31, 2008

That sounds pretty cool Hawkee Image

 Respond  
Hawkee   -  Mar 31, 2008

I agree EL. mIRC is more of a hobby than anything while PHP is a potential career. You should get a shared web hosting account and start a site. We\'re working on some neat new functionality here to allow you to build your site into Hawkee with OpenSocial.

 Respond  
EL   -  Mar 31, 2008

Hey thats cool man.I got no idea hwo to even start in php or shit bu tthis looks useful LOL unlike mIRC no offense but mirc has very little praticial application beyond irc servers/networks so this is neeat to see a piece of coe that most ppl use in forums an such.

 Respond  
Jonesy44   -  Mar 31, 2008

or displaying news from an SQL table with an add feature, i will add an edit/delete function by request.

I\'d agree on the timestamp, so i\'ll add it on later =P

Since the date doens\'t order the list, i havent bothered changing it from varchar :P`

 Respond  
Hawkee   -  Mar 31, 2008

I\'d use a datetime or date and time fields for the date. You shouldn\'t store your date as a varchar. I also suggest adding a timestamp field to indicate the last updated date as well.

You also need a way to edit and delete posts.

 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.