Querying the Database

Query is sent to MySQL asking to see all the records in the classics table, like this:

$query = “SELECT * FROM classics”;
$result = $conn->query($query);

After that, $rows is set to a value representing the number of rows in the table:

$rows = $result->num_rows;

Using the value in $rows, a for loop is then entered to display the contents of each row. Then the program populates the array $row with a row of results by calling the fetch_array method of $result, passing it the constant value MYSQLI_NUM, which forces the return of a numeric (rather than associative) array, like this:

$row = $result->fetch_array(MYSQLI_NUM);

With the data in $row, it’s now a simple matter to display it within the heredoc echo statement that follows, in which I have chosen to use a <pre> tag to line up the display of each record in a pleasing manner.
After the display of each record, there is a second form that also posts to sqltest.php (the program itself) but this time contains two hidden fields: delete and isbn. The delete field is set to yes and isbn to the value held in $row[4], which contains the ISBN for the record.
Then a submit button with the name DELETE RECORD is displayed, and the form is closed. A curly brace then completes the for loop, which will continue until all records have been displayed, at which time the $result and $conn object’s close methods are closed to release resources back to PHP:

$result->close();
$conn->close();

Displaying the Form

program sanitizes copies of the elements we will be outputting from the $row array into the variables $r0 through $r4 by passing them to the htmlspecialchars function, to replace any potentially dangerous HTML characters with harmless HTML entities.
Then the part of code that displays the output follows, using an echo
<<<_END…_END structure as seen in previous chapters, which outputs everything between the _END tags.

Instead of using the echo command, the program could drop out
of PHP using ?>, issue the HTML, and then reenter PHP processing
with <?php. Which style is used is a matter of programmer
preference, but I always recommend staying within PHP code, for
these reasons:

  • It makes it very clear when you’re debugging (and also for other users) that everything within a .php file is PHP code. Therefore, there is no need to go hunting for dropouts to HTML.
  • When you wish to include a PHP variable directly within HTML, you can just type it. If you had dropped back to HTML, you would have had to temporarily reenter PHP processing, access the variable, and then drop back out again.

The HTML form section simply sets the form’s action to sqltest.php. This means that when the form is submitted, the contents of the form fields will be sent to the file sqltest.php, which is the program itself. The form is also set up to send the fields as a POST rather than a GET request. This is because GET requests are appended to the URL being submitted and can look messy in your browser. They also allow users to easily modify submissions and try to hack your server (although that can also be
achieved with in-browser developer tools). Additionally, avoiding GET requests prevents too much information appearing in server log files. Therefore, whenever possible, you should use POST submissions, which also have the benefit of revealing less posted data.

Having output the form fields, the HTML displays a submit button with the name ADD RECORD and closes the form. Note the <pre> and </pre> tags here, which have been used to force a monospaced font that lines up all the inputs nearly. The carriage returns at the end of each line are also output when inside <pre> tags.

Deleting a Record

Prior to checking whether new data has been posted, the program checks whether the variable $_POST[‘delete’] has a value. If so, the user has clicked the DELETE RECORD button to erase a record. In this case, the value of $isbn will also have been posted.
As you’ll recall, the ISBN uniquely identifies each record. The HTML form appends the ISBN to the DELETE FROM query string created in the variable $query, which is then passed to the query method of the $conn object to issue it to MySQL.
If $_POST[‘delete’] is not set (and so there is no record to be deleted), $_POST[‘author’] and other posted values are checked. If they have all been given values, $query is set to an INSERT INTO command, followed by the five values to be inserted. The string is then passed to the query method, which upon completion returns either TRUE or FALSE. If FALSE is returned an error message is displayed, like this:

if (!$result) echo “INSERT failed”;

The $_POST Array

The POST request is usually preferred (because it avoids placing unsightly data in the browser’s address bar), and so we use it here. The
web server bundles up all of the user input (even if the form was filled out with a hundred fields) and puts in into an array named $_POST.

Depending on whether a form has been set to use the POST or the GET method, either the $_POST or the $_GET associative array will be populated with the form data. They can both be read in exactly the same way.

Each field has an element in the array named after that field. So, if a form contains a field named isbn, the $_POST array contains an element keyed by the word isbn. The PHP program can read that field by referring to either $_POST[‘isbn’] or $_POST[“isbn”] (single and double quotes have the same effect in this case).

There is no reason to write to an element in the $_POST array. Its
only purpose is to communicate information from the browser to
the program, and you’re better off copying data to your own variables before altering it.

So, back to the get_post function, which passes each item it retrieves through the real_escape_string method of the connection object to escape any quotes that a hacker may have inserted in order to break into or alter your database, like this:

function get_post($conn, $var)
{
return $conn->real_escape_string($_POST[$var]);
}