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

Note

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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.