How to save the content of an address form to a MySQL database. more >>
CREATE TABLE `addresses` (
`address_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 128 ) NOT NULL ,
`email` VARCHAR( 128 ) NOT NULL ,
`phone` VARCHAR( 128 ) NOT NULL ,
INDEX ( `name` , `email` )
) ENGINE = innodb;
<?php
/**
* Form
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en_US" xml:lang="en_US">
<head>
<title>Form</title>
</head>
<body>
<form method="post" action="save.php">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="addr_name" size="32" /></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="addr_email" size="32" /></td>
</tr>
<tr>
<td>Phone:</td>
<td><input type="text" name="addr_phone" size="32" /></td>
</tr>
</table>
<input type="submit" value="Save" />
</form>
</body>
</html>
<?php
/**
* save
*/
//SQL auth
$host='localhost'; //SQL host
$user='test_user'; //SQL user
$password='test_password';
$database='testing'; //database name
$status="An unexspected error occurred";
$name=$_POST['addr_name'];
$email=$_POST['addr_email'];
$phone=$_POST['addr_phone'];
$connectId = mysql_connect($host, $user, $password);
if($connectId){
if(mysql_select_db($database)){
$query=mysql_query("INSERT INTO `addresses` (`name`, `email`, `phone`) VALUES ('$name', '$email', '$phone')");
$affected=mysql_affected_rows();
echo mysql_error();
if($affected>0){
$status='Address saved';
}
else{
$status='Could not save address';
}
}
else{
$status='Cannot select database';
}
}
else{
$status='Cannot connect to MySQL';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en_US" xml:lang="en_US">
<head>
<title>Save</title>
</head>
<body>
<? echo $status; ?>
</body>
</html>