MANAGING CONTENT // remove backslashes nukeMagicQuotes(); // initialize (Cpanel web hosting)
MANAGING CONTENT // remove backslashes nukeMagicQuotes(); // initialize flag $done = false; // prepare an array of expected items $expected = array(’title’, ‘article’, ‘article_id’); // create database connection $conn = dbConnect(’admin’); // get details of selected record if ($_GET && !$_POST) { if (isset($_GET[’article_id’]) && is_numeric($_GET[’article_id’])) { $article_id = $_GET[’article_id’]; } else { $article_id = NULL; } if ($article_id) { $sql = “SELECT * FROM journal WHERE article_id = $article_id”; $result = mysql_query($sql) or die (mysql_error()); $row = mysql_fetch_assoc($result); } } // redirect page if $article_id is invalid if (!isset($article_id)) { header(’Location: http://localhost/phpsolutions/admin/ . journal_list.php’); exit; } ?> Although this is very similar to the code used for the insert page, the first few lines are outside the conditional statement. Both stages of the update process require the include files, the removal of backslashes, and the database connection, so this avoids the need to duplicate code. The $done flag is initialized as false and will be used later to test whether the update succeeded. There s an important addition to the $expected array. When a record is first inserted, the primary key is generated automatically by MySQL. However, when you update a record, you need its article_id to identify it. The first conditional statement checks that the $_GET array contains at least one value and that the $_POST array is empty. This makes sure that the code inside is executed only when the query string is set, but the form hasn t been submitted. Before building the SQL query, you need to check that $_GET[’article_id’] has been defined and pass it to is_numeric() to make sure that it contains only a number. If someone comes directly to this page or an attacker tries to pass anything else to your query, $article_id is set to NULL. If everything is OK, the SQL query is submitted. The result should contain only one record, so its contents are extracted straight away and stored in $row. 361
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.