Cover by Robin Nixon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

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.

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'); $query = "INSERT INTO classics VALUES" . "('$author', '$title', '$category', '$year', '$isbn')"; if (!mysql_query($query, $db_server)) echo "INSERT ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required