Overview
We'll finish off with a look at server-side scripting, using the language PHP (Pre Hypertext Processor). PHP looks a lot like Javascript, so you already have a foundation in some of the ideas.
In your contact form's action attribute's value, you referenced processor.php as the path to the form handling file.
Create a new page in your texteditor, and save it as processor.php in your html folder.
In PHP you use an open tag <, like the html chicken beak, except this one has a ? and php added, and closes with ?>.
Create open and close php tags as the first step. Insert your cursor between the tags, and get ready to write some code.
In order for this page to see the data that has been sent, we need to access a super global array called $_POST. Remember the attribute in our form, action="post"? $_POST contains all of the data that was submitted by the form. So $_POST['first_name'] contains the user's first name, etc, $_POST['last_name'] contains the user's last name, and $_POST['message'] contains the user's message.
If you put this code in the form's action's path, you can see everything that $_POST contains:
foreach($_POST as $key => $value)
{
echo $key."=".$value."<br/>\n";
}
This basic example shows how php displays the info it receives form an html form:
introduction.html:
Name: <input type="text" name="name" />
Favorite hockey team: <input type="text" name="favorite_hockey_team" />
<input type="submit" />
</form>
welcome.php:
You are a fan of the <?php echo $_POST["favorite_hockey_team"]; ?>.
Here's a simple code to send an email, using the info entered in a contact form:
contact.html:
First name: <input type="text" name="first_name"><br/>
Last name: <input type="text" name="last_name"><br/>
Email: <input type="text" name="email"><br/>
Message: <textarea name="message"></textarea>
</form>
mailer.php:
mail( "ben@fieldii.com", "Message from your site",$_POST['firstname']." ".$_POST['lastname']." writes: ".$_POST['message'], "From: ".$_POST['email']);
echo "Mail sent.";
?>
This code uses a built-in php command called mail. Mail needs at least three arguments-recipient, subject, and message. Ours takes one more - from, or the user's email who sent the form.
- ben@fieldii.com: the email address that the info will be sent to
- Message from your site: The subject of the email
- $_POST['firstname']." ".$_POST['lastname']." writes: ".$_POST['message']: the body of the email, what you read when you get the email
- From: $_POST['email']: the from address, if you reply to the email it will go here
The last line displays a message the user will see when the form goes through.
That's a really quick example of what php can do with a form. This mail script is very simple, and easy to spoof. Use it for learning purposes only! If you use this in a real-world application, it could easily be abused.
PHP and MySQL-Building a basic web app
For the last part of the class, we'll examine how to insert the submitted information into a MySQL database. We'll also build a simple application that will let us search for, edit, and delete information in the database.
Here's a simple ABCDE (Add, Browse, Change, Delete, Edit) php application that lets us do all the things you typically do with mysql: Insert, select, update, and delete records. We will do everything with just one file - simple_app.php. You will need to create the table in your database, and I've included a \ file to do that - create_table.php
Create the database
create_database.php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
mysql_close($con);
?>
Load this page in the browser just once to create the table for your app. Replace the values for username, password, and database name with your own.
Connect to the database and create the table
create_table.php
$connection = mysql_connect("localhost","root");
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $connection);
error_reporting(E_ALL);
ini_set("display_errors", 1);
$page=$_SERVER['PHP_SELF'];
mysql_select_db("test", $connection);
$sql = "CREATE TABLE `test`.`people` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,`FirstName` VARCHAR( 20 ) NOT NULL ,`LastName` VARCHAR( 20 ) NOT NULL ,`Age` INT NOT NULL) ENGINE = MYISAM";
mysql_query($sql,$connection);
mysql_close($connection);
?>
Load this page in the browser just once to create the table for your app. Replace the values for username, password, and database name with your own.
Connect to the database, establish error checking, and a set a commonly used variable
simple_app.php
$connection = mysql_connect("localhost","root","root");
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("learning", $connection);
error_reporting(E_ALL);
ini_set("display_errors", 1);
$page=$_SERVER['PHP_SELF'];
?>
Offer a menu if no task has been assigned
<head>
<title>Simple info management app</title>
</head>
<body>
<?php if(empty($_GET['task']))
{
//break out, just to show another way of doing this to avoid all the echos
?>
Please choose a task:
<a href="<?php echo $page; ?>?task=new">Insert a new person</a>
<a href="<?php echo $page; ?>?task=select">Select an existing person</a>
<?php
//come back into php
}
If the user wants to add a new user, show them the form
{
//break out, just to show another way of doing this to avoid all the echos
?>
<form action="<?php echo $page ?>?task=insert" method="post">
First name: <input type="text" name="firstname" />
Last name: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
<?php
}
After the user submits the form, tell them they were successfull and give them a link back to the menu
{
$sql="INSERT INTO people (FirstName, LastName, Age) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$connection))
{
die('Error: ' . mysql_error());
}
echo "Record added; <a href=\"".$page."\">return to the menu.</a>";
}
If the user wants to choose someone from the table
{
$result = mysql_query("SELECT * FROM people");
echo "<table border='1'>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Age</th>
<th>Edit</th>
<th>Delete</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td><a href=\"".$page."?task=edit&id=".$row['id']."\">Edit this person</td>";
echo "<td><a href=\"".$page."?task=delete&id=".$row['id']."\">Delete this person</td>";
echo "</tr>\n";
}
echo "</table>";
}
If the user chooses someone from the table to edit
{
$result = mysql_query("SELECT * FROM people WHERE id='$_GET[id]'");
$row = mysql_fetch_array($result);
echo "<form action=\"".$page."?task=update&id=".$row['id']."\" method=\"post\">";
echo "First Name: <input type=\"text\" name=\"firstname\" value=\"" . $row['FirstName'] . "\"><br/>\n";
echo "Last Name: <input type=\"text\" name=\"lastname\" value=\"" . $row['LastName'] . "\"><br/>\n";
echo "Age: <input type=\"text\" name=\"age\" value=\"" . $row['Age'] . "\"><br/>\n";
echo "<input type=\"submit\" value=\"Update\">";
}
If the user updates the person they chose
{
$firstname= $_POST['firstname'];
$lastname= $_POST['lastname'];
$age= $_POST['age'];
$id=$_GET['id'];
$result = mysql_query("UPDATE people SET FirstName='$firstname', LastName='$lastname', Age='$age' WHERE id='$id'") or die(mysql_error());
echo "Record updated; <a href=\"".$page."\">return to the menu.</a>";
}
If the user deletes a person
{
$result = mysql_query("DELETE FROM people WHERE id='$_GET[id]'");
echo "1 record deleted; <a href=\"".$page."\">return to the menu.</a>";
}
Exit PHP and finish the html for the page
</body>
</html>
Review
It's time to build your website. To utilize all we've learned in the course, finish the 4 page website we worked with. Use a list to display links on your links page. Use a table to display information about yourself on the about page, e.g., Favorite Restaurant, Dream Car, etc. Create a basic contact form on contact.html with fields for first name, last name, email, and message and make it email the info to you. Add anything and everything to the css to make your site interesting. Have fun!