IM3420 Advanced Scripting Languages

Students will refine dynamic scripting skills to develop complex interactivity and applications (applets). The course also examines client-side forms in conjunction with server-side scripting applications.

Syllabus and Meeting Times

IM3420 Advanced Scripting Languages

Students will refine dynamic scripting skills to develop complex interactivity and applications (applets). The course also examines client-side forms in conjunction with server-side scripting applications. Note: WDIM students must earn a C or better to pass this capstone course

Instructor: John Keston (Schedule)

Meeting Times and Location (M/W):
Session 1 / Session 2
Room 304 (Pence) 2:00pm – 5:00pm

Syllabus:
IM3420 Advanced Scripting Languages

Assignments / Projects:

Projects Due
Guest Book – Stores site guests in a flat file Session 1, Week 4
Links – Store and manage links in a flat file using associative arrays Session 2, Week 6
News – Store and manage news articles in a database Session 1, Week 11
Final Exam Session 2, Week 11

Notice: All the code examples included in the class content for IM3420 Advanced Scripting Languages are what I refer to as skeletons. They are incomplete, some have bugs, and although they may run properly they are not intended for use in production. During the lectures and studio/lab sessions the examples will be developed further and fine tuned. You may use them as a starting point for your projects, but will be expected to improve on the examples and add functionality.

Week 1 | Week 2 | Week 3 | Week 4 | Week 5 | Week 6
Week 7 | Week 8 | Week 9 | Week 10 | Week 11

Week 1

Session 1: Make sure that you can login to your OLS account. Setup a site definition in Dreamweaver or use an FTP client to complete the php tutorial at: http://www.php.net/tut.php from “Your first PHP-enabled page” to “Dealing with forms”.

Recommended Text: “Beginning PHP5” Published by WROX

Reading assignment:
1. Please read everything under variables
http://us2.php.net/manual/en/language.variables.php

2. Please read the following under Operators:
Arithmetic, Assignment, Comparison, Logical and String
http://us2.php.net/manual/en/language.operators.php

Session 2: Create an online guestbook in PHP on your student website. All PHP documents must be contained in your “public_html” directory or sub-directories within it on your OLS account. The guestbook form must have at least 10 fields (First Name, Last Name, Address, etc.) and display the results to the user on a following page. Use text fields, check boxes, radio buttons, select lists and one textarea.

Download: PHP Problem Set 1
1. All PHP problems within a “set” are due by the beginning of class on the next day that the class meets.
2. Answers must be available via links on the OLS or comparable hosting and copied to the drop off drive.
3. Solutions to each problem set will be given during demonstrations on the day that they are due.
4. Grades will be collected during the solution demonstrations by an assigned classmate.

Week 2

Session 1: Now we will continue our discussion on some of the fundamentals of cgi (common gateway interface) scripting, commonly refered to as server side scripting. We’ll look at usefully troubleshooting techniques such as phpinfo() and using the echo statement to display variable values. In the lab make the guestbook form populate the guests.txt flat file Set the permissions to world writable and implement the following code:

<?
    $gb_file = fopen( "guests.txt", "a+" );
    if ( fwrite($gb_file, "$name\t$email\n") ) {
        $body  = "My message Text...\n";
        $body .= "$name\n";
        $body .= "$email\n";
        mail( "my_email@my_domain.edu","Guest Book Entry", $body );
        echo "Thanks!<br>\n";
    }
    else {
        echo "could not write file...<br>\n";
    }
?>

You must create a file in the same folder called “guests.txt” for this example to work. It is also necessary to set the permissions so that the file is “world writable”. The permissions can be set using an FTP client. If you’re unsure how to do this we can go over this in class on Session 1. To check your work, view guest.txt in the browser by going to http://<account_name>.aisites.com/guests.txt

Session 2: Now that your guestbook form is adding each new entry to the “guests.txt” file, create a new php document called “show_guests.php”. Write code in the script to loop through the guests.txt file and display the results in HTML. Make the email field a mailto link ( <a href=”mailto:test@test.com”>test@test.com</a> ). Here’s an example of a loop:

Example #1
<?
        $gb_file = file( 'guests.txt' );
        for( $x=0; $x < count($gb_file); ++$x ) {
                echo ( "line $x:" . $gb_file[$x] . "\n" );
        }
?>


Example #2
<?
    $gb_file = file( 'guests.txt' );
    while( list($line_nums, $lines) = each($gb_file) ) {
        echo( "line $line_nums:" . $lines . "\n" );
    }
?>

Download: PHP Problem Set 2
1. All PHP problems within a “set” are due by the beginning of class on the next day that the class meets.
2. Answers must be available via links on the OLS or comparable hosting and copied to the drop off drive.
3. Solutions to each problem set will be given during demonstrations on the day that they are due.
4. Grades will be collected during the solution demonstrations by an assigned classmate.

Week 3

Session 1: Some important pre-processing is required for text areas within forms, otherwise every time a user hits enter in a text field the flat file will contain the “return” and “new line” characters. This means our flat file will essentially be corrupt because the “new line” character is used to distinguished between one record and the next. The following function replaces the character that corrupts the flat file with an HTML break tag:

$comments = str_replace("\r\n","",$comments); 

It’s easy enough to display the file line by line, but what if you want to have each field within the lines line up within an HTML table and include other formatting options, such as bolding, or a “mailto” link?

In order to do this you need to use the “explode” function to extract the individual fields into an array which we can then display in a dynamic web page. See the example below (show_guests.php):

<html>
<title>My Guests</title>
<head></head>
<body>
<table>
<tr><th>First Name</th><th>Last Name</th><th>Email</th></tr>
<?
    $gb_file = file( 'guests.txt' );
    foreach( $gb_file as $line ) {
        rtrim( $line );
        $field = explode( "\t", $line );
        echo( "<tr>\n" );
        echo( "<td>" . $field[0] . "</td>\n" );
        echo( "<td>" . $field[1] . "</td>\n" );
        echo( "<td><a href=\"mailto:$field[2]\">$field[2]</a></td>" );
        echo( "</tr>" );
    }
?>
</table>
</body>
</html>

Complete the guestbook project by adding your own personal design touch to the elements of the project, including the form (guestbook.html), the action (guestbook.php) and the show_guests.php script. Here’s a list of requirements for the project and how you’re expected to turn in the project:

  1. The guest book form (guestbook.html) must have at least 10 fields for the user to input.
  2. User input must contain arrays by using checkboxes or a select multiple list.
  3. Use loops to gather information from the arrays.
  4. The form action (guestbook.php) must send an email and write the fields to the “guests.txt” file.
  5. The form action must strip harmful header injection attacks.
  6. The guestbook.php script should provide feedback including thanking the user after they submit the form.
  7. The show_guests.php script should display all the guests in a table lined up evenly.
  8. Copy all your code to the drop off drive and a link to your project on OLS.
  9. This project is due Session 2, Week 4.

Session 2: We talked about the dynamic links page project.To begin the links project create a directory called “links” inside your “php” directory. Inside the “links” fold create a form like the one below. The form should have a text field for the url, the category and the description.

Url:
Category:
Description:

To see a working model of the links project click here.

Download: PHP Problem Set 3
1. All PHP problems within a “set” are due by the beginning of class on the next day that the class meets.
2. Answers must be available via links on the OLS or comparable hosting and copied to the drop off drive.
3. Solutions to each problem set will be given during demonstrations on the day that they are due.
4. Grades will be collected during the solution demonstrations by an assigned classmate.

Week 4

Session 1: Don’t forget that the “guestbook” project is due today. Create the link to the working guestbook area and copy the source files with the link file (this includes the form html document, the form’s action PHP, and the PHP script to display the guests) to the drop off drive (John Keston\mm2421\<student_name>).

Write a PHP script to alphabetically display a list of categories found in the links.txt file using multi-dimensional associative arrays. This may sound hard, but it’s only 15 lines of code. Using associative arrays makes it possible to organize data such that very little code is needed to handle more complicated tasks. Here’s an example to help you along:

<?
  // include this at the very top of index.php
  // open the links file and insert into array
  $links_file = file( 'links.txt' );

  // loop through the file, line by line
  foreach ($links_file as $line ) {
    $line = rtrim( $line );
    $field = explode( "\t", $line );
    // make sure a category and link exist
    if ( $field[0] && $field[1] ) {
      // set the description to the link if absent
      if ( !$field[2] ) {
        $field[2] = $field[1];
      }
      // push each link into a hash of each category - this creates
      // a multidimensional associative array called $links_hash
      $links_hash["$field[0]"][]="<a href=\"$field[1]\">$field[2]</a>";
    }
  }
  // sort the hash by the key ("category")
  ksort ( $links_hash );
?>
<?
  // place this in the body of index.php
  // Display the Categories as links to anchors
  echo( "<b>Categories:</b><br />\n" );
  while ( list($key,$value) = each($links_hash) ) {
    echo( "<a href=\"#$key\">$key</a><br />\n" );
  }
  reset( $links_hash );
?>

Session 2: Here’s an example of code which will display all the links after they have been placed in the hash called $links_hash. This code must be placed in the same document AND after the code example from Session 1.

<?
  // add to body of index.php
  while( list($key, $value) = each ($links_hash) ) {
    echo( "<p><a href=\"#top\" name=\"$key\"><b>$key</b></a><br />\n" );
    sort ( $value );
    for ( $x=0; $x < count($value); ++$x ) {
      echo( "$value[$x]<br>\n" );
    }
  }
?>

Download: PHP Problem Set 4
1. All PHP problems within a “set” are due by the beginning of class on the next day that the class meets.
2. Answers must be available via links on the OLS or comparable hosting and copied to the drop off drive.
3. Solutions to each problem set will be given during demonstrations on the day that they are due.
4. Grades will be collected during the solution demonstrations by an assigned classmate.

Week 5

Session 1: What if you want to make sure that none of the links you’re adding to the links file are duplicates? You’re not going to want the same link in the same page twice and it may be difficult to remember every link that you’ve added. Here’s an example of how you can prevent duplicate links from being added to the flat file:

<?
    import_request_variables("gP");
    // Check for a new category
    if ( $new_category ) {
        $category = $new_category;
    }

    // Make sure $url and $category exist before adding
    if ( $url && $category ) {
        $links_file = file ( 'links.txt' );
        for( $x=0; $x < count($links_file); ++$x ) {
            $field = explode( "\t", $links_file&#91;$x&#93; );
            $match = rtrim( $field&#91;1&#93; );
            // Check for duplicate links
            if ( $match == $url ) {
                header( "Location: index.php?message=duplicate link" );
                exit( );
            }
        }
        $links_file = fopen( 'links.txt', "a+" );
        if ( $description ) {
            $new_link = "$category\t$url\t$description\n";
        }
        else {
            $new_link = "$category\t$url\n";
        }
        fwrite( $links_file, $new_link );
        fclose( $links_file );
    }
    header( "Location: index.php" );
?>

Session 2: If you have gotten as far as getting the links added while avoiding duplicates and displaying the links organized by category, then it’s time to add the functionality to delete links. To do this you will need to search through your flat file and re-write the information without the link specified for deletion. Here’s an example of code which will accomplish this task:

<?
    // File: drop_link.php 
    // Author: John Keston
    // Description: Drop a link from the the links flat file
            
    import_request_variables("gP");
    $message = "Link not found";
 
    if ( $drop_url ) {
        $links_file = file ( 'links.txt' );
        foreach( $links_file as $line ) {
            $field = explode( "\t", $line );
            $field&#91;2&#93; = rtrim( $field&#91;2&#93; );
            if ( !$field&#91;2&#93; ) {
                $field&#91;1&#93; = rtrim( $field&#91;1&#93; );
            }
            if ( $field&#91;1&#93; != $drop_url && $field&#91;2&#93; != $drop_url ) {
                $new_file&#91;&#93; = $line;
            }
            else {
                $message = "";
            }
            // Uncomment this line for troubleshooting
            // echo ( "<pre>|$drop_url|$field[1]|$field[2]|\n" );
        }
        $new_links = fopen( 'links.txt', "w+" );
        foreach( $new_file as $link ) {
            fwrite( $new_links, $link );
        }
        fclose( $new_links );
    }
    header( "Location: index.php?message=$message" );
?>

Week 6

Session 1: The links project is due on Session 2, Week 6. This project and the guestbook project is what will determine your midterm grade, please add any finishing touches before Session 2. Most of you have this included already, but to add a dynamically generated drop down list of categories to the add link form use the following code. Make sure that you place the code within the form tags of the add link form:

<select name="category">
<?
    while ( list($key,$value) = each($links_hash) ) {
        echo( "<option value=\"$key\">$key</option>\n" );
    }
    reset( $links_hash );
?>
</select>

To turn in the links project, on the drop off drive (Z:/John Keston/mm2421/<yourname>/links) place the following:

  1. An Internet Shortcut to your “links” project
  2. All the source code
  3. The “links.txt” flat file
  4. Add at least 5 categories with a total of at least 20 links to your page
  5. Add some personal design choices to your links page

The next project is called the News Database project and involves making a web interface to a remote database. We’ll use MySQL which is the database platform, and PHPMyAdmin as our tool for managing the database. Add the following tables to your student webspace database. Add at least one user with username and password to the users table:

CREATE TABLE news_users (
    id          INT PRIMARY KEY AUTO_INCREMENT,
    username    VARCHAR(64)        NOT NULL UNIQUE,
    password    VARCHAR(64)        NOT NULL,
    first_name  VARCHAR(64)        NOT NULL,
    last_name   VARCHAR(64)        NOT NULL,
    email       VARCHAR(128),
    status      VARCHAR(32) DEFAULT 'enabled'
);

CREATE TABLE news_articles (
    id          INT PRIMARY KEY AUTO_INCREMENT,
    headline    VARCHAR(128)        NOT NULL,
    author      VARCHAR(128),
    body        TEXT                NOT NULL,
    create_date DATETIME            NOT NULL,
    modify_date DATETIME,
    user_id     INT                 NOT NULL,
    status      VARCHAR(32) DEFAULT 'enabled'
);

Session 2: The links project is due today. Next step is to write the code which authenticates the user and sets a session cookie so that we know who has authenticated and use their ID to track who’s creating the news stories. Place these examples in a sub-directory of your php directory called “news”. Next create a login form then create a php script called “auth_user.php” to compare what the user enters to the database.

1. The “Login” form:

Username:
Password:
<?
    ////////////////////////////////
    // Script Name: auth_user.php //
    ////////////////////////////////
    import_request_variables("gp");

    // Connect to a MySQL database
    $dbh = mysql_connect ("localhost", "jck362aii_jck", "abc123")
        or die ('I cannot connect to the database.');
    mysql_select_db ("jck362aii_news");

    // Build the database query
    $query = "SELECT * FROM news_users WHERE ";
    $query .= "username = '$username' AND ";
    $query .= "password = MD5('$password') AND ";
    $query .= "status = 'enabled'";
    // Execute the query and fetch the results
    $result = mysql_query($query);
    $row = mysql_fetch_array($result);
    // check for a match
    if ( $row ) {
        // Set a cookie and display the add news form
        setcookie( "user_id",$row['id'] );
        header( "Location: add_news.php" );
        exit();
    }
    // Return to login.php and displays auth failed message
    header( "Location: login.php?" .
            "message=Authorization failed. Please try again." );
?>

Week 7

Session 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&#91;'user_id'&#93;;
  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&#91;"user_id"&#93;;
  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”);

Week 8

Session 1: Now we can move on the the “front-end” of the application. This is where users can view news that has been inserted into the database. The first page will list all the news stories in the database as links and the links for each story will display the details of the story. Here’s the code for the list of stories (show_headlines.php):

<html>
<head>
<title>Show Headlines</title>
</head>
<body>
<h3>News Stories</h3>
<b><font color="red"><? echo $message ?></font></b>
<table>
<tr><th>Headline</th><th>Author</th><th>Date</th>
<?
    /////////////////////////////////////
    // Script Name: show_headlines.php //
    /////////////////////////////////////

	include('connect_inc.php');

    $query  = "SELECT *,DATE_FORMAT(create_date,'%W, %M %D, %Y') ";
    $query .= "AS pretty_date ";
    $query .= " FROM news_articles WHERE status = 'enabled' ";
    $query .= "ORDER BY create_date DESC ";

    $results = mysql_query($query);
    while( $row = mysql_fetch_array($results) ) {
        // create alternating background colors
        ++$x;
        $bgcolor = "#ffffff";
        if ( $x % 2 ) {
            $bgcolor = "#cccccc";
        }
        // display the headlines in html table rows
        echo ("<tr bgcolor=\"$bgcolor\">\n");
        echo ("<td><a href=\"show_news.php?id=".$row[id]."\">");
        echo ("$row[headline]</a></td>\n");
        echo ("<td>$row[author]</td>\n");
        echo ("<td>$row[pretty_date]</td>\n");
        echo ("</tr>");
    }
?>
</table>
</html>

Challenge: Try to make the column header work as links to sort by that column. Also, clicking twice makes the sort direction change from ascending (ASC) to descending (DESC). Click here for an example.

News Project Milestone #1
1. Login with session authentication is working
2. check_auth.php verifies administrative user (add_news and insert_news)
3. Adding news articles is working
4. show_headlines.php is working

MySQL Documentation for the DATE_FORMAT function

Session 2: Now we need to write the script called “show_news.php” which will display the entire news story. The first part of the script is PHP and the latter part is mostly HTML. What’s happening is that we are selecting the information from the database and then displaying it in one step.

<?
  ////////////////////////////////
  // Script Name: show_news.php //
  ////////////////////////////////
  $message = "News story not available";
  import_request_variables("gP");
  if ( !is_numeric($id) ) {
    header( "Location: show_headlines.php?message=$message" );
    exit();
  }
  include('connect_inc.php');

  $query  = "SELECT * FROM jck_news ";
  $query .= "WHERE id = $id";
  $results = mysql_query($query);

  $row = mysql_fetch_array($results);
  if ( !$row ) {
    header( "Location: show_headlines.php?message=$message" );
    exit();
  }
?>
<html>
<head>
</head>
<body>
<h2><?= $row['headline'] ?></h2><b>
Author: <?= $row['author'] ?><br>
Date: <?= $row['create_date'] ?>
</b>
<p>
<?= $row['body'] ?>
</body>
</html>

Week 9

Session 1: Now our news project is nearly fully functional, but in order to remove or archive news articles we would have to access the database and “manually” remove records or change the status of those records. A better solution would be to create a page that allows the user to delete or archive news by pressing a button.

Start by “re-purposing” the code that is in place for “show_headlines.php” creating a new script in the admin directory called “modify_news.php”. Include the code which checks the cookie so that the page is secure and add in forms with hidden variables and buttons to archive and delete the records.

<?
  // modify_news.php
  // Make sure that the user has authenticated
  $user_id = $_COOKIE&#91;"user_id"&#93;;
  if ( !$user_id ) {
    header( "Location: login.php?message=Please login before modifying news" ); 
    exit();
  }
?>
<html>
<title>Modify News</title>
<head></head>
<font color="red"><? echo $_GET&#91;message&#93; ?></font>
<table>
<tr>
<th>Headline</th><th>Author</th><th>Create Date</th><th>Status</th>
</tr>
<?
  include("connect_inc.php");
  $query  = "SELECT * FROM jck_news ";
  $query .= "ORDER BY status, create_date DESC";

  $results = mysql_query($query);
  while( $row = mysql_fetch_array($results) ) {
    echo ( "<tr><td><a href=\"update_form.php?id=$row&#91;id&#93;.\">" .
           "$row[headline]</a></td>" .
           "<td>$row[author]</td><td>$row[create_date]</td>\n" .
           "<form method=\"post\" action=\"change_status.php\">" );
    $selected[$row[status]] = ' selected="selected"';
    echo ( "<td><select name=\"status\">" );
    echo ( "<option value=\"enabled\" $selected&#91;enabled&#93;>Enabled</option>\n" );
    echo ( "<option value=\"disabled\" $selected&#91;disabled&#93;>Disabled</option>\n" );
    echo ( "<option value=\"archived\" $selected&#91;archived&#93;>Archived</option>\n" );
    echo ( "</select></td>\n" );
    echo ( "<input type=\"hidden\" name=\"id\" value=\"$row&#91;id&#93;\">" );
    echo ( "<td><input type=\"submit\" value=\"Change Status\">" );
    echo ( "</td>\n</form>\n</tr>\n" );
        
    // clear the $selected hash
    unset( $selected );
  }
?>

Session 2: Here’s a good way to build the change_status.php script. Make sure that you remember to replace all the location paths and table names with the appropriate values. This script also uses a function. Functions are way to write code that you can reuse by calling the function.

<?
  // change_status.php
  // Make sure that the user has authenticated
  $user_id = $_COOKIE&#91;"user_id"&#93;;
  if ( !$user_id ) {
    header( "Location: login.php?" .
            "message=Please login before modifying news" );
    exit();
  }
  function update_status ($id, $status) {
    include ("connect.php");
    $query  = "UPDATE jck_news SET status='$status' ";
    $query .= "WHERE id = $id";
    return mysql_query($query);
  }
  if ( update_status($_POST&#91;id&#93;, $_POST&#91;status&#93;) ) {
    $message = "Set news article $_POST&#91;id&#93; status to $_POST&#91;status&#93;";
    header ("Location: modify_news.php?message=$message" );
    exit();
  }
  else {
    $message = "Update Failed";
    header ("Location: modify_news.php?message=$message" );
    exit();
  }
?>

Week 10

Session 1: The last step that we’ll take in the administrative area is building the functionality necessary to allow administrators to completely update a news article in the database via a web form. This will require two scripts the first script will be the form, prefilled, so that the administrator can edit the data, and the second (standalone) script will include the UPDATE query. Here’s the source for the first script:

<?
  // update_form.php
  // Make sure that the user has authenticated
  $user_id = $_COOKIE&#91;"user_id"&#93;;
  if ( !$user_id ) {
    header( "Location: login.php?message=Please login before updating news" ); 
    exit();
  }
  if (!$_GET&#91;id&#93;) {
    header( "Location: modify_news.php?message=No such news article" ); 
    exit();
  }
  // Connect to database
  include ("connect.php");
  // Build query 
  $query = "SELECT * FROM jck_news WHERE id = $_GET&#91;id&#93;";
  $result = mysql_query( $query );
  if (!$result) {
    header( "Location: modify_news.php?message=Query failed: $query" ); 
    exit();
  }
  $row = mysql_fetch_array( $result );
  $selected&#91;$row&#91;status&#93;&#93; = "SELECTED";
?>
<html>
<title>Update News Article</title>
<head></head>
<body>
<form action="update_news.php" method="post">
<input type="hidden" name="id" value="<? echo $row&#91;id&#93; ?>">
Headline: 
<input type="text" name="headline" value="<? echo $row&#91;headline&#93; ?>"><br />
Author: 
<input type="text" name="author" value="<? echo $row&#91;author&#93; ?>"><br />
Create Date: 
<input type="text" name="headline" value="<? echo $row&#91;create_date&#93; ?>"><br />
Status:<br />
<select name="status">
<option value="enabled"<?= $selected&#91;enabled&#93; ?>>Enabled</option>
<option value="enabled"<?= $selected&#91;disabled&#93; ?>>Disabled</option>
<option value="enabled"<?= $selected&#91;archived&#93; ?>>Archived</option>
<br />
<textarea name="body"><? echo $row&#91;body&#93; ?></textarea><br />
<input type="submit" value="Update"><input type="reset" value="Reset">
</form>
</body>
</html>

Session 2: Finally we need the script which actually updates the record in the database. We will call this standalone PHP script update_news.php as it is called in the form action in update_form.php. Here’s the source for update_news.php:

<?
  // update_news.php
  // Make sure that the user has authenticated
  $user_id = $_COOKIE&#91;"user_id"&#93;;
  if ( !$user_id ) {
    header( "Location: login.php?message=Please login before updating news" ); 
    exit();
  }
  // Connect to database
  include ("connect.php");
  import_request_variables("gP");
  // Build query 
  $query  = "UPDATE jck_news SET headline='$headline', ";
  $query .= "author='$author', create_date='$create_date', ";
  $query .= "modify_date=NOW(), body='$body', status='$status', ";
  $query .= "user_id=$user_id WHERE id=$id";

  if ( mysql_query($query) ) {
    header( "Location: modify_news.php?message=News article id: $id updated." ); 
    exit();
  }
  header( "Location: modify_news.php?message=Update failed: $query" );
?>

Week 11

Session 1: Today we will be reviewing for the final quiz. Afterwards in the studio, let’s add some final touches to the news project. Early presentations of the news project are acceptable as well.

Session 2: The final quiz is today. Afterwards we will discuss the questions and then present the news projects.