A Practical Example

It’s time to write our first example of inserting data in and deleting it from a MySQL table using PHP. I recommend that you type in Example 10-8 and save it to your web development directory using the filename sqltest.php. You can see an example of the program’s output in Figure 10-2.

The output from , sqltest.php
Figure 10-2. The output from Example 10-8, sqltest.php


Example 10-8 creates a standard HTML form. The following chapter explains forms in detail, but in this chapter I take form handling for granted and just deal with database interaction.

Example 10-8. Inserting and deleting using sqltest.php
<?php // sqltest.php require_once 'login.php'; $db_server = mysql_connect($db_hostname, $db_username, $db_password); if (!$db_server) die("Unable to connect to MySQL: " . mysql_error()); mysql_select_db($db_database, $db_server) or die("Unable to select database: " . mysql_error()); if (isset($_POST['delete']) && isset($_POST['isbn'])) { $isbn = get_post('isbn'); $query = "DELETE FROM classics WHERE isbn='$isbn'"; if (!mysql_query($query, $db_server)) echo "DELETE failed: $query<br />" . mysql_error() . "<br /><br />"; } if (isset($_POST['author']) && isset($_POST['title']) && isset($_POST['category']) && isset($_POST['year']) && isset($_POST['isbn'])) { $author = get_post('author'); $title = get_post('title'); $category = get_post('category'); $year = get_post('year'); $isbn = get_post('isbn'); ...

Get Learning PHP, MySQL, and JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.