<!DOCTYPE html 
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <title>New Contact</title>
</head>
<body>
<h1>Add a new contact</h1>
<?php
//Include constants file; this file simply defines two constants,
//DB_USERNAME and DB_PASSWORD.
require_once('constants.php');

if (isset(
$_POST['submitted'])) {
    
//The form was submitted; let's add a new contact to the database
    
$first_name $_POST['first_name'];
    
$last_name  $_POST['last_name'];
    
$phone      $_POST['phone'];
    
$state      $_POST['state'];
    
    
//Let's check to see if the details submitted were valid
    
if (empty($first_name) || empty($last_name) || empty($phone) || empty($state)) {
        echo 
"<p>Error: You must specify all fields.</p>";
    } else {
        
//Connects to the database server
        
if (!mysql_connect('localhost'DB_USERNAMEDB_PASSWORD)) {
            exit(
'No connection');
        }
        
        
//Selects the appropriate database (uchiyama_test is the name of our database)
        
if (!mysql_select_db('uchiyama_test')) {
            exit(
'Cannot select database');
        }
        
        
//Build the insertion query
        
$query "INSERT INTO addressbook ("
        
."first_name, last_name, phone, state) VALUES ("
        
."'".mysql_real_escape_string($first_name)."',"
        
."'".mysql_real_escape_string($last_name) ."',"
        
."'".mysql_real_escape_string($phone)     ."',"
        
."'".mysql_real_escape_string($state)     ."'"
        
.")";
                
        echo 
"<p>The query was:</p><pre>$query</pre>";
        
        
//Actually execute the insertion query
        
if (!mysql_query($query)) {
            exit(
'Insert failed '.mysql_error());
        }
        
        echo 
"Added contact successfully!";
    }

} else {
    
//The form wasn't submitted; the user came directly to this page.
    //Let's just display the form.
?>
    <form method="post" action="newcontact.php">
    <div style="line-height: 180%">
    <input type="hidden" name="submitted" value="yes" />
    First name: <input type="text" name="first_name" size="30" />
    <br />Last name: <input type="text" name="last_name" size="30" />
    <br />Phone number: <input type="text" name="phone" size="20" />
    <br />State: <input type="text" name="state" size="2" maxlength="2" />
    <br /><input type="submit" value="Add contact" />
    </div>
    </form>
<?php
}
?>
<hr />
<div><a href="listcontacts.php">List contacts</a></div>
</body>
</html>