Week 7
December 4, 2007 – 9:45 pmSession 1: Once you have database authentication working create the add_news.php script which will check to make sure that the user_id cookie has been written and if so display the “Add News” form similar to what’s below. At the top of the form document insert the PHP code below to test for the cookie value.
The “Add News” form:
| Headline: | |
| Topic: | |
| Author: | |
| Date: | |
| Body: |
|
<?
$user_id = $_COOKIE['user_id'];
if ( !$user_id ) {
header( "Location: login.php?message=Login before adding news" );
exit();
}
?>
Now that we are authenticating the administrative users and creating a cookie, we need to send them to the news form so they can add a news story. Here’s an an example of code we can use to insert a record into the news table:
<?
//////////////////////////////////
// Script Name: insert_news.php //
//////////////////////////////////
import_request_variables("gP");
$user_id = $_COOKIE["user_id"];
if ( !$user_id ) {
header( "Location: login.php?message=Login before adding news" );
exit();
}
// Connect to a MySQL database
$dbh=mysql_connect ("localhost", "mydb_account", "mydb_password")
or die ('I cannot connect to the database.');
mysql_select_db ("mydb_name");
// Build the database query
$query = "INSERT INTO jck_news ";
$query .= "(headline,author,body,create_date,user_id,status) ";
$query .= "VALUES ";
$query .= "('$headline','$author','$body',");
$query .= "'$create_date',$user_id,'$status')";
// Execute the query and check for validity
if ( mysql_query($query) ) {
header("Location: add_news.php?message=Thanks for your submission");
exit();
}
echo( "insert failed: $query\n" );
?>
Session 2: Today let’s discuss how we can take frequently used code and put it into includes. Includes work like functions and are reusable chunks of code that we can link in our PHP documents, rather than re-writing things repeatedly.
connect_inc.php
<?
// Connect to a MySQL database
$dbh=mysql_connect ("localhost", "mydb_account", "mydb_password");
mysql_select_db("mydb_name");
?>
Use the following line of code to include the connection script in a diferent PHP document:
include(“connect_inc.php”);