Web page design - BLOG DESIGN SOLUTIONS Stepping through the code, the
Sunday, December 23rd, 2007BLOG DESIGN SOLUTIONS Stepping through the code, the first line extracts the post_id from the query string: $post_id = (isset($_REQUEST[”post_id”]))?$_REQUEST[”post_id”]:”"; Next, the preg_match function uses a regular expression to check that the post_id is a number. This is important for two reasons. First, from a practical point of view, the only valid post_ids are numbers, so there is no point dealing with post_ids that are not numbers. Second, from a security point of view, anyone can type anything into a query string, so it s vital to filter out any potentially harmful input. So if a valid-looking post_id has been identified, a flag (by way of the variable editmode) is set so the script knows it is in edit mode (this will be used later): if (preg_match(”/^[0-9]+$/”, $post_id)) { $editmode = true; Using regular expressions is a way of searching and matching patterns in text. The syntax is complex and seemingly obscure, but they are nonetheless a fast and powerful method of performing extremely specific searches and replace- ments in text. If you want to learn more about regular expressions, I recommend Nathan A. Good s book Regular Expression Recipes (for more details see www.apress.com/book/bookDisplay.html?bID=396). Next, an SQL query is used to extract the post from the database. The query is constructed using a SELECT statement of this form: SELECT required fields FROM database table WHERE condition is met This query is then sent to the database using the mysql_query function. On the next line, the mysql_fetch_array function is used to put the first row of SQL query result into an array; because each post_id is unique, there will be only one row returned anyway. This array is stored in the variable $mypost. If the SELECT statement did not return any results, the value of $mypost is null, and a warning is written to $message. If $mypost is not null, the values of the $mypost array are put into individual variables. Note that the elements of the array correspond to the column names in the SELECT statement: $result = mysql_query($sql); $mypost = mysql_fetch_array($result); if($mypost) { $title = $mypost[”title”]; $postdate = $mypost[”postdate”]; $summary = $mypost[”summary”]; $post = $mypost[”post”]; } else { $message = “No post matching that post_id.”; } The next step is to repopulate the form with the post pulled out of the database. For each input box, add a value attribute and echo the corresponding PHP variable: