Free web design training service and resources by the Rochester Web Wizard @ Data Info Magic

Free web design training guide and resources by the Rochester Web Wizard. Sponsored by Data Info Magic.

Lesson 7 : Putting it All Together: HTML,CSS, PHP & MySQL

This is the database application written from scratch and all hand coded and can be written using completely free software. Take a look at the Database Application to see how things work.You will be required to log in to access the Database Application.

There are three steps that you may need to go through.

1. HTML Forms: You should now look into HTML Forms so that you can enter, delete, update and print tables from your database. It isn't difficult to put the two things together. Here's a place to start: PHP Forms Tutorial.

2. Separate Forms and PHP/MySQL You can learn to make the forms and PHP/MySQL separately first. I have a tutorial available that I used at Database Samples. I furnished most of the code for it in lesson 6 for you to use and I also have a working application to try. I take it really slowly but it's a good way to review what you've done so far. It only covers the basics but in a very clear and simple way. This is a good intermediate step if you have no database experience or you aren't a programmer. The examples do not touch on any kind of MySQL security so they are not appropriate for online use. You should only test these on your local server.

These demonstrations use a database, test. with the several tables. You can use 2 different files dbinfo.inc.php and dbinfo2.inc.php one for your local machine and one for the remote host. Then you only need to change 1 line of code in each file before uploading to your host server. The code should look like this:

<?/* local or remote connection*/
$server="localhost";
$username="your user name";
$password="your password";
$database="test";
?>

Then in each file put in the lines:

include ("dbinfo.inc.php");
$db=@mysql_connect($server,$username,$password);
if(!($db))
{
echo "Connection failed.";
exit;
}
$dbn=@mysql_select_db($database);
if(!($dbn))
{
echo "Database not found.";
exit;
}

You can get the script to create the tables for the database here: test script

Once you feel comfortable with these then you should move on.

The following is for HostMonster only.

Other hosting companies will have their own prcedure for setting up PHP and MySQL.

If you want to try MySQL/PHP programs on HostMonster now: You will need to request the setup of your MySQL database. It will include up to 99 databases for free with no size limit! Log into your account. On the CPanel page you will see your username. Every database name and MySQL user will begin with this prefix "username_". Do not enter it when naming your databases or users. It will be appended automatically. It will save you time if you use the same convention on your local server so you don't need to change any code when you upload your PHP files. Never have any user enter a username or database name with the prefix. Use PHP concantenation to append it after it is entered. Towards the bottom of the CPanel you will see the Datbases panel:

CPanel

You will use the phpMyAdmin application exactly the same way as your local machine. The exception is when you create a new database and users with permissions. That happens at the MySQL Databases application. The easiest way to transfer your MySQL local files to your server or vise versa is to dump your database to a .sql file and copy and run the script in the SQl window of phpMyAdmin on either server or DreamCoder for MySQL on your local machine.

 

 

3. When you have finished the 2 steps above then:Take a look at the Database Application to see how things work.You will be required to log in to access the Database Application. I will get you started with some sample code. If you use this as a blueprint for your code then you should have no problem completing the remainder of the project code. This is really a stripped down version with no CSS Style Sheet attached and some security features left off. I have additional security to discourage hackers and to protect my propriatary code. The pages have an HTML part that you can see plus a PHP part that you can not see when you execute it in your browser. It contains simple but standard PHP/MySQL/JavaScript security called AJAX. This prevents SQL injection plus unauthorized access. You would normally NOT furnish the login information, but it is for educational purposes. There are also restrictions placed on the guest users by the database administrator. I also have protected pages so that users need to log on to acccess them. Make an index.html page with links to your other pages. You should be able to complete the code for the other pages by replacing the MySQL query and modifying the code.

 

 

Critical Message!!!

You should always test things on your local server before uploading to the Web. Restrict the user on the Server to the most restrictive permissions that you can. Normally I would not allow guest users to have add, update or delete privileges.

 

 

Don't forget the basics!!!

You can use PHPMyAdmin or DreamCoder (locally) to check the values of the database tables as you go along. You can get the necessary information to connect from your hosting company.

Important Tip: Even though MySQL code is not case sensitive nor does it require indenting, make sure to follow the conventions for readibility, especially for yourself.

Reminder: You need to have XAMMP including the Apache Server and PHP installed and running to try PHP locally. Your HostMonster account already has Apache Server and PHP set up and ready to go but you need to request setup for a MySQL database. For other Hosts you will need to check on their particular procedure and whether they support it. All you need to do is change the file extention to .php and add your PHP code to the HTML. A PHP page can still run HTML code. You just nee to start <? and stop ?> the PHP code.

The 4 items that you must always know when dealing with a database on the local server (Apache installed on your machine) and remote server (HostMonster) are:

1. Host is localhost

2. User Name is root

3. Password is can be left blank on the local machine so don't enter one initially.

4. Database name is whatever you choose and Table is also. One database may have many tables.

They can be the same on the remote server (The server set up by HostMonster or your current hosting company), except ALWAYS USE A PASSWORD AND SET YOUR USER PERMISSIONS AS STRICTLY AS POSSIBLE!!!!!

 

 

AJAX isn't just for cleaning anymore!


 

A little background explaination is called for before you begin, particularly in the add.php file which contains the most security and validation code. I used both client-side validation (PERL and JavaScript) and server-side validation in my AJAX code.

Whenever you make a form you should not leave it alone without any form validation. Why? Because there is no guarantee that the input is correct and processing incorrect input values can make your application give unpredictable result.

You can validate the form input on two places, client-side and server-side. Client side form validation usually done with javascript. Client side validation makes your web application respond 'faster' while server side form validation with PHP can act as a backup just in case the user switch off javascript support on her browser. And since different browsers can behave differently there is always a possibility that the browser didn't execute the javascript code as you intended.

AJAX = Asynchronous JavaScript and XML. AJAX is based on JavaScript and HTTP requests. AJAX is a type of programming made popular in 2005 by Google (with Google Suggest). AJAX is not a new programming language, but a new way to use existing standards.

PERL (Practical Extraction and Report Language) is a relatively new language. It was created in 1986 by Larry Wall. It has gone through a versions Perl, Perl4, and, the newly released Perl5. Perl's strength lies in it's ability to interact with it's environment. It is a very powerful string manipulation language. It is able to open and manipulate many files from within the same program, with ease.

What is SQL Injection

SQL injection refers to the act of someone inserting a MySQL statement to be run on your database without your knowledge. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a MySQL statement that you will unknowingly run on your database.

 

PHP/MySQL Database Application

Using either DreamCoder or PHPMyAdmin, create a database named test2. Create a project folder called MySQL Project. Create an images folder inside.

dbinfo.inc.php


Type the following code into a file called dbinfo.inc.php

<?
$username="root";
$password="your password";
$database="your database name";
?>

Modify the code according to your own names! They could be different from your local server.

 

Create Database & Table


Using either DreamCoder or PHPMyAdmin, Create a database and keep track of the name for your code. Create a project folder called Database Project. Create an images folder inside. Then run setup.php once to create the table. Enter a few names and data to get started using phpMyAdmin or DreamCoder (locally). Use the server, username and password that you set up on your local server. Change them in the code if necessary. These values must match!

In setup.php, add the following code in the body:

<?
include("dbinfo.inc.php");
mysql_connect(localhost,$username,$password);

@mysql_select_db($database) or die( "Unable to select database");

$query="CREATE TABLE contacts (
id int(6) NOT NULL auto_increment,
first varchar(15) NOT NULL,last varchar(15) NOT NULL,
phone varchar(20) NOT NULL,mobile varchar(20) NOT NULL,
fax varchar(20) NOT NULL,email varchar(30) NOT NULL,
web varchar(30) NOT NULL,PRIMARY KEY (id),
UNIQUE id (id),KEY id_2 (id))";

mysql_query($query);
mysql_close();
echo "Database created";
?>

 

 

add.php


Here is an outline of the code in add.php.

Most of the code in add.php is commented using //single line comments or /*multiple line comments*/ ( uncomment lines of code for debugging when desired) and it uses the following specific validation in the code in approximately this order:

1. Contains required fields.

2. Keeps an array of errror messages.

3. Checks the email format using PERL.

4. Checks the phone number format using PERL.

5. Checks the database name.

6. Checks to see if there are any warnings.

7. If there is at least one warning then the form is recalled (This is called recursion in programming.) and you must fix the errors. The error message is displayed beside each incorrect field on the form. This is repeated until the form is filled out correctly. The form is not cleared .

8. If there are no warnings then the form is processed and: The field variables are cleaned (checked for SQL injection). The username, password and database name you entered are compared to the values in the dbinfo.inc.php file. The connection is made to the database. The MySQL query is executed. The user is notified that the operation was a success.


In add.php, add the following code in the body:

<?php
include("dbinfo.inc.php");
$server="localhost";

mysql_connect($server,$username,$password);

// prevents SQL injection
function cleanQuery($string)
{
if(get_magic_quotes_gpc()) // prevents duplicate backslashes
{
$string = stripslashes($string);
}
if (phpversion() >= '4.3.0')
{
$string = mysql_real_escape_string($string);
}
else
{
$string = mysql_escape_string($string);
}
return $string;
}
?>
<!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">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>add.php</title>
</head>
<body>
<p>&nbsp;</p>
<p>Back to <b><a href="index.html">Main Page</a></b>&nbsp;&nbsp;</p>
<h2>&nbsp;</h2>
<h2>Add people to your database</h2>
<h1>&nbsp;</h1>
<hr size="1" />
<p>This page has an HTML part that you can see plus a PHP part that you can not see. It contains simple but standard PHP/MySQL/JavaScript security called AJAX. This prevents SQL injection plus unauthorized access. You would normally NOT furnish the login information, but this is for educational purposes. There are also restrictions placed on the guest users by the database administrator.</p>
<?php
// Field name labels
$required=array("first"=>"First Name",
"last"=>Last Name",
"phone"=>"Phone Number",
"email"=>"Email",
"street"=>"Street",
"city"=>"City",
"zip"=>"Zip",
"contact"=>"Contact",
"username1"=>"User Name",
"password1"=>"Password",
"database1"=>"Database Name");

foreach($required as $field=>$label)
{
if(!$_POST[$field])
{
$warnings[$field]="<=Required";
}
}

if($_POST["email"]&&!ereg("^[^@]+@([a-z0-9\-]+\.)+[a-z]{2,4}$", $_POST['email']))
$warnings["email"]="<=invalid Email";

if($_POST["phone"]&&!ereg("^\([[:digit:]]{3}\)[[:digit:]]{3}-[[:digit:]]{4}$", $_POST['phone']))
$warnings["phone"]="<=invalid Phone Number Must be in the form (555)555-5555";

$link = mysql_connect($server,$username,$password);
mysql_select_db("your database name", $link);

if(count($warnings)>0 )
{
?>
<center>
<H2>Add a Contact</H2>
</center>
<center>
<FORM ACTION="add.php" METHOD=POST>
<TABLE width="600" height="200 px" BORDER=5 cellpadding="5" cellspacing="5" bordercolor="#333333" bgcolor="#999999">
<TR>
<TD bgcolor="#CCCCCC"><span class="style3">First Name</span></TD>
<TD bgcolor="#CCCCCC"><input NAME="first" TYPE="text" VALUE="<?php echo $_POST["first"];?>" SIZE="50"></TD>
<TD bgcolor="#999999"><span class="style3"><font color="#FF0000"><?php echo $warnings["first"];?></span></TD>
</TR>
<TR bgcolor="#669999">
<TD bgcolor="#CCCCCC"><span class="style3">Last Name</span></TD>
<TD bgcolor="#CCCCCC"><input NAME="last" TYPE="text" VALUE="<?php echo $_POST["last"];?>" SIZE="50"></TD>
<TD bgcolor="#999999"><span class="style3"><font color="#FF0000"><?php echo $warnings["last"];?></span></TD>
</TR>
<TR bgcolor="#669999">
<TD bgcolor="#CCCCCC"><span class="style3">Phone Number</span></TD>
<TD bgcolor="#CCCCCC"><input NAME="phone" TYPE="text" VALUE="<?php echo $_POST["phone"];?>" SIZE="50"></TD>
<TD bgcolor="#999999"><span class="style3"><font color="#FF0000"><?php echo $warnings["phone"];?></span></TD>
</TR>
<TR bgcolor="#669999">
<TD bgcolor="#CCCCCC"><span class="style3">Email Address</span></TD>
<TD bgcolor="#CCCCCC"><input NAME="email" TYPE="text" VALUE="<?php echo $_POST["email"];?>" SIZE="50"></TD>
<TD bgcolor="#999999"><span class="style3"><font color="#FF0000"><?php echo $warnings["email"];?></span></TD>
</TR>
<TR bgcolor="#669999">
<TD bgcolor="#CCCCCC"><span class="style3">Street and Number</span></TD>
<TD bgcolor="#CCCCCC"><span class="style3">
<input TYPE="text" NAME="street" SIZE="50" VALUE="<?php echo $_POST["street"];?>">
</span></TD>
<TD bgcolor="#999999"><span class="style3"><font color="#FF0000"><?php echo $warnings["street"];?></span></TD>
</TR>
<TR bgcolor="#669999">
<TD bgcolor="#CCCCCC"><span class="style3">City and State</span></TD>
<TD bgcolor="#CCCCCC"><input NAME="city" TYPE="text" VALUE="<?php echo $_POST["city"];?>" SIZE="50"></TD>
<TD bgcolor="#999999"><span class="style3"><font color="#FF0000"><?php echo $warnings["city"];?></span></TD>
</TR>
<TR bgcolor="#669999">
<TD bgcolor="#CCCCCC"><span class="style3">Zip Code</span></TD>
<TD bgcolor="#CCCCCC"><input NAME="zip" TYPE="text" VALUE="<?php echo $_POST["zip"];?>" SIZE="50"></TD>
<TD bgcolor="#999999"><span class="style3"><font color="#FF0000"><?php echo $warnings["zip"];?></span></TD>
</TR>
<TR bgcolor="#CCCCCC">
<TD><span class="style3">Contact Type</span></TD>
<TD><span class="style3">
<SELECT NAME="contact">
<OPTION>Phone
<OPTION>Email
<OPTION>Mail
<OPTION>In Person
<OPTION>Do Not Contact
</SELECT>
</span></TD>
</TR>
<tr bgcolor="#999999">
<td bgcolor="#666666"><p class="style4">&nbsp;</p>
<p class="style4 style5">You must enter the correct Username, Password and Database to complete the submission.</p>
<p class="style4">&nbsp;</p></td>
<td bgcolor="#666666"><p class="style4">These values are all case sensitive.</p></td>
</tr>
<TR bgcolor="#66CC99">
<TD bgcolor="#666666"><span class="style3">User Name</span></TD>
<TD bgcolor="#666666"><input name="username1" type="password" value="<?php echo $_POST["username1"];?>" size="20" /></TD>
<TD bgcolor="#999999"><span class="style3"><font color="#FF0000"><?php echo $warnings["username1"];?></span></TD>
</TR>
<TR>
<TD bgcolor="#666666"><span class="style3">Password</span></TD>
<TD bgcolor="#666666"><input NAME="password1" TYPE="password" VALUE="<?php echo $_POST["password1"];?>" SIZE="20"></TD>
<TD><span class="style3"><font color="#FF0000"><?php echo $warnings["password1"];?></span></TD>
</TR>
<TR>
<TD bgcolor="#666666"><span class="style3">Database Name</span></TD>
<TD bgcolor="#666666"><input NAME="database1" TYPE="password" VALUE="<?php echo $_POST["database1"];?>" SIZE="20"></TD>
<TD><span class="style3"><font color="#FF0000"><?php echo $warnings["database1"];?></span></TD>
</TR>
</TABLE>
<INPUT TYPE="reset" VALUE="Clear Form">
<input type="Submit">
</FORM>
</center>
</div>
<?php
}
else
{
echo "Thank you.<br>";

/* Check all form inputs using cleanQuery function */
$first = cleanQuery($_POST['first'], "Enter your first name");
$last = cleanQuery($_POST['last'], "Enter your last name");
$phone = cleanQuery($_POST['phone'],"Enter your phone number");
$email = cleanQuery($_POST['email'],"Enter your email");
$street = cleanQuery($_POST['street'],"Enter your street and #");
$city = cleanQuery($_POST['city'],"Enter your city & state");
$zip = cleanQuery($_POST['zip'],"Enter your zip code");
$contact = cleanQuery($_POST['contact'], "Write your contact method");

//use for debugging
//echo("Here is the information you submitted<br>");
//echo("first=".$first."<br/> last=".$last."<br/> phone=".$phone."<br/> email=".$email."<br/>
street=".$street."<br/> city=".$city."<br/> zip=".$zip."<br/>contact=".$contact );

//Save data to the database table
$username1=$_POST['username1'];
$password1=$_POST['password1'];
$database1=$_POST['database1'];

//use for debugging
//echo $username;echo $password;echo $database;
//echo $username1;echo $password1;echo $database1;


if($username==$username1 && $password==$password1 && $database==$database1)
{
@mysql_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO contacts VALUES ('','$first','$last','$phone','$email','$street','$city','$zip','$contact')";
mysql_query($query);
mysql_close();
}
else
{
echo "<br>Sorry. Your username or password didn't match. Please try again!<br>";
}
?>
<p>You have successfully added a contact to your database.</p>
<p align="center">Back to the <a href="home.php" title="main menu"> Main Page</a></p>
<p>&nbsp;</p>
<?php
}
?>
</body>
</html>

This is almost impossible to read without the proper indentation. If you are using RapidPHP ro Dreamweaver then you can format the code for readability. Otherwise you may wish to get the code from add.pdf instead.

 

 

display.php


In display.php, add the following code in the body:


?>
<!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">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>display.php</title>
</head>
<body>
<p>&nbsp;</p>
<p>Back to the <b><a href="index.html">Main Page</a></b>&nbsp;</p>
<h1>display.php</h1>
<h2>&nbsp;</h2>
<h2>Display all of the your database table.</h2>
<hr size="1" />
<p>This page has an HTML part that you can see plus a PHP part that you can not see. It contains simple but standard PHP/MySQL/JavaScript security called AJAX. This prevents SQL injection plus unauthorized access. You would normally NOT furnish the login information, but this is for educational purposes. There are also restrictions placed on the guest users by the database administrator.</p>
<h2>Login to view the table</h2>
<hr size="1" />
<p>Enter the login information into the form below.</p>
<center>
<FORM ACTION="display.php" METHOD=POST>
<TABLE width="600" height="200 px" BORDER=5 cellpadding="5" cellspacing="5" bordercolor="#333333" bgcolor="#999999">
<TR>
<TD>User Name</TD>
<TD><input name="username1" type="password" value="<?php echo $_POST["username1"];?>" size="20" /></TD>
<TD><font color="#FF0000"><?php echo $warnings["username1"];?></TD>
</TR>
<TR>
<TD>Password</TD>
<TD><input NAME="password1" TYPE="password" VALUE="<?php echo $_POST["password1"];?>" SIZE="20"></TD>
<TD><font color="#FF0000"><?php echo $warnings["password1"];?></TD>
</TR>
<TR>
<TD>Database Name</TD>
<TD><input NAME="database1" TYPE="password" VALUE="<?php echo $_POST["database1"];?>" SIZE="20"></TD>
<TD><font color="#FF0000"><?php echo $warnings["database1"];?></TD>
</TR>
</TABLE>
<p>
<INPUT TYPE="reset" VALUE="Clear Form">
<input type="Submit">
</p>
<p>You must enter the correct username, password and database name to view the table.</p>
<p>They are avaiilable on the main page. These values are all case sensitive.</p>
<p>&nbsp; </p>
</FORM>
</center>
<center>

<?
include ("dbinfo.inc.php");
$db=@mysql_connect($server, $username,$password);
if(!($db))
{
echo "Database connection failed.";
exit;
}
$dbn=@mysql_select_db($database);
if(!($dbn))
{
echo "Database not found.";
exit;
}
//Save data to the database table
$username1=$_POST['username1'];
$password1=$_POST['password1'];
$database1=$_POST['database1'];

//for debugging purposes only
//echo $username;echo $password;echo $database;
//echo $username1;echo $password1;echo $database1;


if($username==$username1 && $password==$password1 && $database==$database1)
{
// Get all the data from the "example" table
$result = @mysql_query("SELECT * FROM contacts")
or die("Error.");

echo "<table border='2'>";
echo "<tr><th>Index</th> <th>First</th> <th>Last</th><th>Phone</th><th>Email</th><th>Street</th><th>City</th><th>Zip</th>

<th>Contact</th>
</tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['id'];
echo "</td><td>";
echo $row['first'];
echo "</td><td>";
echo $row['last'];
echo "</td><td>";
echo $row['phone'];
echo "</td><td>";
echo $row['email'];
echo "</td><td>";
echo $row['street'];
echo "</td><td>";
echo $row['city'];
echo "</td><td>";
echo $row['zip'];
echo "</td><td>";
echo $row['contact'];

echo "</td></tr>";
}
echo "</table>";
}
else
{
echo "<br>Sorry. Your username or password didn't match. Please try again!<br>";
}
?>

</p>
</center>

</body>
</html>

This is almost impossible to read without the proper indentation. If you are using RapidPHP or Dreamweaver then you can format the code for readability. Otherwise you may wish to get the code from display.pdf instead. You can get the code for search, sort, update and delete here... Code.

 

 

Don't stop now!!!

Congratulations, if you made it this far !!!

You are not ready to go professional but you do know enough to decide if you would like to pursue it.

Where do you go after this?

After this lesson I would suggest upgrading to DreamWeaver. I also purchased many of the extensions from WebAssist but they are not inexpensive. At least now you will know enough to make a judgement as to whether this is for you or not before laying out a lot of cash.

I have created the same database application using DreamWeaver and DataAssist. It is much more expensive to do but it cuts the devlopment time by 90% by automatically creating all of the code through a wizard. I would not reccommend it to anyone who is not very knowlegable about HTML, CSS, PHP and MySQL code first. It is also not worth it unless you will be using the datafiles commercially.

But hand coding is still the fastest and simplest way to edit php/MySQL files. Dealing with endless menus can bog you down infinitely!

At least now you know enough to make a judgement as to whether this is for you or not before laying out a lot of cash.

I have created the same database application using DreamWeaver and DataAssist. It is much more expensive to do but it cuts the devlopment time by 90% by automatically creating all of the code through a wizard. I would not reccommend it to anyone who is not very knowlegable about HTML, CSS, PHP and MySQL code first. It is also not worth it unless you will be using the datafiles commercially. Select this link to view the application and learn More...

You must also log in to view the WebAssist Application.

Now is the time to catch your breath and enjoy

your accomplishments!

Good luck and have fun.

 

 
Back to Main Menu