Download 3.Dealing (again) with forms in Php

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

IMDb wikipedia , lookup

Oracle Database wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Ingres (database) wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

SQL wikipedia , lookup

Concurrency control wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Database wikipedia , lookup

Open Database Connectivity wikipedia , lookup

PL/SQL wikipedia , lookup

Relational model wikipedia , lookup

ContactPoint wikipedia , lookup

Clusterpoint wikipedia , lookup

Database model wikipedia , lookup

Transcript
Php Programming Concepts and Database Driven Web Applications
3. Dealing (again) with forms in Php
The most important thing to notice when dealing with HTML
forms and PHP is that any form element in an HTML page will
automatically be available to the PHP scripts.
3.1 Revising how forms work
Example 1: A simple HTML form:
<form action="action.php" method="post">
<p>Your name: <input type="text" name="name" /></p>
<p>Your age: <input type="text" name="age" /></p>
<p><input type="submit" /></p>
</form>
There is nothing special about the form: it is a straight HTML
form with no special tags of any kind. When the user fills in this form
and hits the submit button, the action.php page is called. The
action.php script could look like this:
Hi <?php
echo htmlspecialchars($_POST['name']);
?>.
You are
<?php echo (int)$_POST['age'];
?>
years old.
The function htmlspecialchars() makes sure any characters that
are special in html are properly encoded so users can't inject HTML
tags or Javascript into the page. For the age field, since it is known
53
Php Programming Concepts and Database Driven Web Applications
that it is a number, it was just converted to an integer which will
automatically get rid of any stray characters.
$_POST superglobal contains all POST data. The method of the
form is POST. If the method GET is used, then the form information
would live in the $_GET superglobal instead. It also may be used the
$_REQUEST superglobal, if no care about the source of the request
data. It contains the merged information of GET, POST and COOKIE
data.
So, anything submitted via the POST method is available in the
$_POST array.
It is important to notice that the index of the $_POST array is the
name given to the HTML form element. Whatever the form element is
called (a form element being a button, textbox, checkbox, etc), that is
what the index of the $_POST array will be in order to access the data
from that element.
The next example will show a method using a single .php file,
combining both PHP and HTML in one simple text file, to retrieve the
data and display the results.
Below is a quick review of bullets, check boxes, text fields, and
input fields and using them to build a form to retrieve some personal
information about a user.
Input fields are the simplest forms to grasp. When defining them,
it is compulsory to place the name attribute within the tags and specify
a name for the field. Also for the form's action attribute it is used the
$PHP_SELF super global in order to send the form to itself.
<html>
<head><title>Personal INFO</title></head>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
<!-- Input Fields -->
First Name:
<input type="text" size="12" maxlength="12"
name="Fname">:<br />
Last Name:
<input type="text" size="12" maxlength="36"
name="Lname">:<br />
54
Php Programming Concepts and Database Driven Web Applications
<! -- Radios and Checkboxes -->
Gender::<br />
Male:
<input type="radio" value="Male" name="gender">:<br />
Female:
<input type="radio" value="Female"
name="gender">:<br />
Please choose favorite course:<br />
Math:
<input type="checkbox" value=“Math"
name=“course[]">:<br />
Informatics:
<input type="checkbox" value=“Informatics" name="
course[]">:<br />
Psychology:
<input type="checkbox" value=“Psychology" name="
course[]">:<br />
<! -- textarea -->
<textarea rows="5" cols="20" name="quote“
wrap="physical">
Enter your favorite quote!
</textarea>:<br />
<! -- Drop Down Lists & Selection Lists -->
Select a Level of Education:<br />
<select name="education">
<option value=“Bachelor"> Bachelor </option>
<option value="HighSchool">HighSchool</option>
<option value="College">College</option></select>:<br />
Select your favorite time of day::<br />
<select name="TofD" size="3">
<option value="Morning">Morning</option>
<option value="Day">Day</option>
<option value="Night">Night</option></select>:<br />
<! -- Submission Button -->
<input type="submit" value="submit"
name="submit"><br />
</form>
<br />
The output display should look like this:
55
Php Programming Concepts and Database Driven Web Applications
Retrieving form data and setting up variables: in PHP there is an
array used to call data from the form. It’s a superglobal of PHP and
it’s one that is great to have memorized. $_POST retrieves the form
data and outputs it directly to the browser. The best way to do this (as
already discussed), is to make variables for each element in the form,
so to output this data at will, using own variable names. Placing the
following lines of code just before the form ending tag (</form>) and
using the correct PHP syntax will realize that:
<?php
$Fname = $_POST ["Fname"];
$Lname = $_POST ["Lname"];
$gender = $_POST ["gender"];
$course = $_POST ["course"];
$quote = $_POST ["quote"];
$education = $_POST ["education"];
$TofD = $_POST ["TofD"];
?>
56
Php Programming Concepts and Database Driven Web Applications
This part of code consists in making easier variable names for the
form output. With the above statements, the call of the data will be
easy! For the form action, the PHP’s $PHP_SELF array variable will
be called. This array is set up to call itself when submitted. Basically,
the form is set up to call the php script itself.
At this point, there is a completed form with correct action and
submission. Next we need to do a little programming to achieve what
we want displayed before and after a certain event: before the user
submits any information we need to first direct them to the form
(obviously) and second, we will display their results using the variable
names.
PHP offers an excellent way to create this effect using an if
statement placed as shown:
<?php
if (isset ($_POST ['submit'])) {
$Fname = $_POST ["Fname"];
$Lname = $_POST ["Lname"];
$gender = $_POST ["gender"];
$course = $_POST ["course"];
$quote = $_POST ["quote"];
$education = $_POST ["education"];
$TofD = $_POST ["TofD"];
echo "Hello, ".$Fname." ".$Lname.".<br />";
echo "You are ".$gender.", and you like ";
foreach ($course as $c) { echo $c."<br />"; }
echo "<i>".$quote."</i><br />";
echo "Your time is ".$TofD.", and you passed
".$education."!<br />";
}
?>
</form></html>
Looking again at the form, filling it and submitting the data, the
result should look like this:
57
Php Programming Concepts and Database Driven Web Applications
3.2 Validating forms
It is essential to have the input to our form validated before taking
the form submission data for further processing. When there are many
fields in the form, the PHP validation script could become complex,
but there are some simple examples, as following.
Let’s see the example HTML code bellow.
<html><body>
<form action="myform.php" method="post">
<p>Your Name: <input type="text" name="yourname"
/><br />
E-mail: <input type="text" name="email" /></p>
<p>Do you like this website?
<input type="radio" name="likeit" value="Yes"
checked="checked" /> Yes
<input type="radio" name="likeit" value="No" /> No
<input type="radio" name="likeit" value="Not sure"
/> Not sure</p>
58
Php Programming Concepts and Database Driven Web Applications
<p>Your comments:<br />
<textarea name="comments" rows="10"
cols="40"></textarea></p>
<p><input type="submit" value="Send it!"></p>
</form>
</body></html>
This is a simple HTML form with two input fields, one radio box
group and a text area for comments. Let's say we save this code in a
file called “test.html”. When submitted, data is sent to the
“myform.php” file using POST HTTP method. All variables passed to
the current script via the HTTP POST method are stored in associative
array $_POST. So, access data from each field using
$_POST[‘NAME’], where NAME is the actual field name.
To display submitted data we could simply echo all the variables
as shown below:
<html><body>
Your name is: <?php echo $_POST['yourname']; ?><br
/>
Your e-mail: <?php echo $_POST['email']; ?><br />
<br />
Do you like this website? <?php echo
$_POST['likeit']; ?><br />
<br />
Comments:<br />
<?php echo $_POST['comments']; ?>
</body>
</html>
If you saved this code in a file called “myform.php”, filled the
fields in the contact.html form and hit the Submit button, the
myform.php output would look something like this:
59
Php Programming Concepts and Database Driven Web Applications
But the most important thing is still missing! It is necessary to
validate submitted data to protect the script (and thus the website and
server) from malicious code.
1. The very least we should do is pass all variables through PHP’s
htmlspecialchars() function. This function will replace HTML chars
like < and > to their HTML version &lt; and &gt;.
This is much safer now and prevents possible attackers from
exploiting our code by injecting HTML or Javascript code:
<?php
$yourname = htmlspecialchars($_POST['yourname']);
$email
= htmlspecialchars($_POST['email']);
$likeit
= htmlspecialchars($_POST['likeit']);
$comments = htmlspecialchars($_POST['comments']);
?>
<html> <body>
Your name is: <?php echo $yourname; ?><br />
Your e-mail: <?php echo $email; ?><br />
Do you like this website? <?php echo $likeit; ?><br
/>
Comments:<br />
<?php echo $comments; ?>
</body></html>
60
Php Programming Concepts and Database Driven Web Applications
To ensure that the user has entered what we want let’s do two
more things:
2. strip unnecessary characters from the data
3. remove slashes if quotes are escaped with a slash “\ “
Instead of writing the same code over and over again we can
create a function that will do all the checking for us. Here we will
name it check_input and simply call this function whenever it is
necessary to validate simple input data.
So, the php script would look like this:
<?php
$yourname = check_input($_POST['yourname']);
$email
= check_input($_POST['email']);
$likeit
= check_input($_POST['likeit']);
$comments = check_input($_POST['comments']);
?>
<html><body>
Your name is: <?php echo $yourname; ?><br />
Your e-mail: <?php echo $email; ?><br />
Do you like this website? <?php echo $likeit; ?><br
/>
Comments:<br /><?php echo $comments; ?>
</body></html>
<?php
function check_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
So far, the examples worked only with optional fields – in all
previous examples the scripts worked fine even if the user didn’t enter
any data. However, most of a times it is necessary to make input fields
required.
Let’s edit the check_input function like this:
61
Php Programming Concepts and Database Driven Web Applications
function check_input($data, $problem=‘’)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
die($problem);
}
return $data;
}
It was added an extra parameter to the form: $problem: by
default $problem is empty, but if passing a value for $problem to the
function and the length of entered data is 0 the script will stop
executing (die) displaying the text passed as $problem parameter.
Now, in order to make the field “yourname” required we can
simply add , “Error message” to the function call, like this:
$yourname = check_input($_POST['yourname'],”Enter
your name!”);
$email
= check_input($_POST['email'], “Enter your
email!”);
$comments = check_input($_POST['comments'], “Enter
comments!”);
Now if the “yourname” fields is empty when the form is
submitted, the script will stop and display “Enter your name!” text.
As a result, if the “yourname” fields is empty when the form is
submitted, the script will stop and display “Enter your name!” text.
The final php script would look like this:
<?php
$yourname = check_input($_POST['yourname'], "Enter
your name");
$email
= check_input($_POST['email']);
$likeit
= check_input($_POST['likeit']);
62
Php Programming Concepts and Database Driven Web Applications
$comments = check_input($_POST['comments'], "Write
your comments");
?>
<html><body>
Your name is: <?php echo $yourname; ?><br />
Your e-mail: <?php echo $email; ?><br />
Do you like this website? <?php echo $likeit; ?><br />
Comments:<br />
<?php echo $comments; ?>
</body></html>
<?php
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
die($problem);
}
return $data;
}
?>
It can be observed that the first and the last field are required and
the second and third are optional because we have used the
check_input function with a second parameter value.
Bellow are displayed the screens with the result when the field
“comments” is not filled by the user – the die() PHP function just
displays the error text:
63
Php Programming Concepts and Database Driven Web Applications
4. How to validate e-mail address and URL
The two examples below show the use of preg_match() function.
a. Checking if the e-mail address syntax is valid:
$email = htmlspecialchars($_POST['email']);
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
{
die("E-mail address not valid");
}
The function preg_match perform a regular expression match.
preg_match() returns 1 if the pattern matches given subject, 0 if it
does not, or FALSE if an error occurred.
b. Checking if URL address syntax is valid (when having an
input field named “website”):
$url = htmlspecialchars($_POST['website']);
if (!preg_match("/^(https?:\/\/+[\w\-]+\.[\w\]+)/i",$url))
{
die("URL address not valid");
}
64
Php Programming Concepts and Database Driven Web Applications
5. Other special cases:
a. Digits 0-9 only – this code will check if $age is a number:
if (preg_match("/\D/",$age)) {
die("Please enter numbers only for Age");
}
b. Letters a-z and A-Z only – this code will check if $text is
made of letters a-z and A-Z only (no spaces, digits or any
other characters):
if (preg_match("/[^a-zA-Z]/",$text)) {
die("Please enter letters a-z and A-Z only!");
}
c. Anything but whitespace – this code will show an error if
$text contains of any whitespace characters (space, tab,
newline):
if (preg_match("/\s/",$text)) {
die("Please do not enter any spaces, tabs or new
lines!");
}
65
Php Programming Concepts and Database Driven Web Applications
4. Interacting with a database: PHP – MySQL
4.1 Some specifications and review
With the advent of new design trends on the Web, rich and
dynamic web applications have been flooding the Internet. As we
have already discussed, developing a web application is not as simple
as a making a static HTML website – since it requires a serious jump
from simpler client-side languages (i.e., languages which are
interpreted by the site visitors’ browser) like HTML and JavaScript, to
the server-side languages like PHP and MySQL, both of which
happen to be open-source.
As opposed to the client-side technologies which can be tested
using a simple web browser, server-side technologies require software
to be installed on a web server – which is basically a computer which
processes the server-side script when a visitor requests for it, creates
the required page, and sends it over the visitor's computer.
There are many server-side technologies, for example the
proprietary ASP (Active Server Pages) from Microsoft, Ruby On
Rails, Perl, et al. Each one with its own feature set, each with its own
advantages/disadvantages – but the technology that powers most of
the current websites is called the LAMP architecture. LAMP stands
for Linux, Apache, MySQL, PHP; basically what it signifies is that
most servers out there today run on Linux machines, with this
powerful server software called Apache – which in turn acts as an
interpreter for server-side scripts written in PHP, and for reading
stored data from MySQL databases.
The fact that these are all open source projects means that these
versatile software can be set up for free, and then extended according
to own needs using the impressive amount and variety of plugins
written for these software.
66
Php Programming Concepts and Database Driven Web Applications
So, we need to get backend software running to interpret PHP and
MySQL. But before getting start with running online, it is better to try
first on our own computer. According to its name, EasyPHP is a single
package that combines Apache, PHP and MySQL, installs easy and
quickly, and requires no configuration. It has a complete graphical
user interface, thereby increasing the ease of use.
The menu offered by the EasyPHP software is shown in the next
figure and explained bellow:
Help – Brings up a couple help sites.
Log Files –Allows to open Apache’s and MySQL’s warning/error
logs. This is where any errors which occur will be noted down by the
software for future.
Configuration – Brings up a sub-menu linking to some of the
configuration files and programs.
Explore – Launches Windows Explorer to show the web's root
directory – the place where are kept the web pages. This folder can also
be manually found, at C:\Program Files\EasyPHP \www\
Administration – Loads the EasyPHP administration web site.
Local Web – Launches the default web browser and loads the
web site.
Restart – Restarts the MySQL and Apache servers. If changing
settings, it may be needed.
Start / Stop – Start or Stops the MySQL and Apache servers.
Exit – Quits EasyPHP. This will also stop the MySQL and
Apache servers if they aren't installed as services.
67
Php Programming Concepts and Database Driven Web Applications
4.2 MySql connect
Before doing anything with MySQL in PHP, first of all it is
necessary to establish a connection to the web host's MySQL
database. This is done with the MySQL connect function.
In the following example of a connection script, we assume that
the MySQL service is running on the same machine as the script. So,
when the PHP script and MySQL are on the same machine, we can
use localhost as the address we wish to connect to.
localhost is a shortcut to just have the machine connect to itself (if
the MySQL service is running at a separate location we will need to
insert the IP address or URL in place of localhost).
The mysql_connect function takes three arguments: server,
username, and password. In the following example these arguments are:
• Server – localhost
• Username – root
• Password – mysql
The “or die(mysql...” code displays an error message in the
browser if there is an error in processing the connection!
Example code:
<?php
mysql_connect("localhost", "root", "mysql") or
die(mysql_error());
echo "Connected to MySQL <br />";
?>
If the above PHP script run on the webserver and everything works
properly, then the message “Connected to MySQL” will be displayed.
4.3 Choosing the Working Database
After establishing a MySQL connection with the code above, then
it is needed to choose which database will be used with this
connection. This is done with the mysql_select_db function.
Example code:
68
Php Programming Concepts and Database Driven Web Applications
<?php
mysql_connect("localhost", "root", "mysql") or
die(mysql_error());
echo "Connected to MySQL<br />";
mysql_select_db("test") or die(mysql_error());
echo "Connected to Database";
?>
If there is a database named test the result will display the
messages:
Connected to MySQL Connected to Database
The following code is used to show standard operations when
working with a database:
– Connecting, selecting database;
– Performing a SQL query;
– Printing results in HTML;
– Closing connection.
<?php
// Connecting, selecting database
$link = mysql_connect('mysql_host', 'mysql_user', 'm
ysql_password')
or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
mysql_select_db('my_database') or die('Could not sel
ect database');
// Performing SQL query
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed:
' . mysql_error());
// Printing results in HTML
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSO
C)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
69
Php Programming Concepts and Database Driven Web Applications
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Closing connection
mysql_close($link);
?>
4.4. phpMyAdmin – Creating a database
The phpmyadmin tool consists of PHP scripts, web interfaces
MySQL database administration and can create/delete databases,
create/delete/alter tables, add/delete/edit fields, execute SQL
statements and manage key fields. Typing in the browser address
window http://127.0.0.1/phpmyadmin/ the following window will
appear:
Note: before accessing http://localhost/phpmyadmin
phpMyAdmin folder has to be copied in the www folder.
the
4.4.1. What is a database
A database is a way to store lots of information. We might want
to store the names and addresses of all our contacts, or save usernames
and passwords for our online forum. In a database, we save the
information in a Table.
70
Php Programming Concepts and Database Driven Web Applications
A single database can contain many tables, and they can be linked
together. When the tables are linked together, the database is a
relational database. In the case of a single table in the database, it is
called a flat-file database.
Flat-file database are easier to create and understand, so the next
steps explain how to create one of these using phpMyAdmin.
We are going to create a simple Address Book, so we type that
into the textbox:
After that, in the new area we can create a Table to go in our
database. At the moment, as it says, there are No tables found in the
database. But the database itself has been created.
To create a new table, we type a name for it in the box at the
bottom and also a number for the Fields textbox. The fields are the
columns, and will be things like first_name, surname, address, etc.
More can be added later, but our example looks like below:
71
Php Programming Concepts and Database Driven Web Applications
4.4.2 Setting up the fields (name and type)
In the next window the user establishes a name and a type for
each field.
So we have given each column in
our table a name: ID, First_Name,
Surname, and Address. The next
thing to set is what type of data will
be going in to each field - do we want
to store text in this field, numbers,
Yes/No value, etc?
To set the type of data going into a field, we select
an item from the Type drop down list.
Clicking the down arrow the following list appears
to choose from:
Integer Values:
TINYINT Signed: – 128 to 127. Unsigned: 0 to 255
SMALLINT Signed: – 32768 to 32767. Unsigned: 0
to 65535
MEDIUMINT Signed: – 8388608 to 8388607.
Unsigned: 0 to 6777215
INT Signed: – 2147483648 to 2147483647.
Unsigned: 0 to 4294967295
BIGINT Signed: – 9223372036854775808.
Unsigned: 0 to 18446744073709551615
72
Php Programming Concepts and Database Driven Web Applications
Text Types:
TINYTEXT 256 bytes
TEXT 64 KiloBytes
MEDIUMTEXT 16 MegaBytes
LONGTEXT 4 GigaBytes
Char, Varchar
The signed and unsigned are for minus and non minus values. So
if we need to store negative values, we need to be aware of the signed
ranges. If we were using a TINYINT value, for example, we can go
from minus 128 to positive 127 and if we did not we can go from 0 to
positive 255.
For our address book, we have an ID field. We are using this just
to identify a record (row). Each record will be unique, so it will need a
different number for each. We can set it to one of the INT values. But
which one?
If we set ID to TINYINT, then we would run in to problem if we
tried to store more than 255 records. If we used SMALLINT,
problems could appear if we tried to stored the details of friend
number 65536. So, if we have more than 65 and half thousand friends,
then we need a different INT type, but now we’ll assume that we
don't, so we’ll use SMALLINT.
Null
This is an important field in database terminology. It essentially
means, „Should the field contain anything?” If setting a field to NOT
NULL, then it can not be left blank, otherwise we’ll get errors.
Default
When adding a new record, the default value will automatically
appear in the field.
Extra
This is where we can set an auto increment value. This means
adding one to the previous record number. This is ideal for us, as we
have an ID field. Then we don't have to worry about this field.
MySQL will take care of updating it for us.
73
Php Programming Concepts and Database Driven Web Applications
4.4.3 Finishing the table’s logical structure
The final step in order to finish the logical structure of the table is
to set a primary key for the ID field by selecting the radio button, and
choose Auto Increment from the Extra drop down list :
4.4.4 Open and Close a connection to a database with
PHP – review
• Step 1 – Open a connection to MySQL itself
• Step 2 – Specify the database we want to open
• Step 3 – Close the connection
<?PHP
$user_name = "root";
$password = "";
74
Php Programming Concepts and Database Driven Web Applications
$database = "addressbook";
$server = "127.0.0.1";
$db_handle
=
mysql_connect($server,
$user_name,
$password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
print "Database Found ";
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
}
?>
4.5 MySQL databases – read records with PHP
To read records from a database, the technique is usually to loop
round and find the ones we want. To specify which records we want,
we use SQL (Structured Query Language).
Having now a connection to our database, the next script read all
the records, and print them out to the page.
<?php
$user_name = "root";
$password = "";
$database = "addressbook";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM tb_address_book";
$result = mysql_query($SQL);
while ( $row = mysql_fetch_array($result) ) {
print $row ['ID'] . "<BR>";
print $row ['First_Name'] . "</br>";
print $row ['Surname'] . "</br>";
print $row ['Address'] . "</br>";
}
mysql_close($db_handle);
}
75
Php Programming Concepts and Database Driven Web Applications
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
Explanations:
The first line in the new code is this:
$SQL = “SELECT * FROM tb_address_book”;
The $SQL is just a normal variable. But we are putting into it a
long string: a SQL statement.
SQL is a way to query and manipulate databases. If we want to
grab all of the records from a table in a database, we use the SELECT
construction. Like this:
SELECT * FROM Table_Name
So we have a SQL statement, but we need to pass it to another
inbuilt function:
mysql_query( )
The mysql_query( ) function is used to send a SQL query to our
database. If we have typed out our SQL correctly, then the function
will return a value. This value will be true, false, or a file handle. The
file handle returned in our $result variable that just points to the
results. It doesn’t actually bring anything back.
The inbuilt function we are using to bring results back is this:
mysql_fetch_array( $result )
4.5.1. The steps used to read records from database –
review
1. Set up a SQL Statement that can be used to get the records
from the database table
2. Use mysql_query() to bring back the records we've specified
in Step 1
3. Use mysql_fetch_array() to set up an array. The array will
contain all the records that were returned in Step 2
4. Loop round all the data in the array using a While loop
76
Php Programming Concepts and Database Driven Web Applications
Step 1:
$SQL = “SELECT * FROM tb_address_book”;
Step 2:
$result = mysql_query($SQL);
Step 3:
$db_field = mysql_fetch_assoc($result);
And Step 4 was this:
while ($row = mysql_fetch_array($result)) {
print $row [‘ID’] . “</br>”;
print $row [‘First_Name’] . “</br>”;
print $row [‘Surname’] . “</br>”;
print $row [‘Address’] . “</br>”;
}
4.6. Add a record to a MySQL database
Now we will adapt the code to add more records to our database
table.
To add records to a table, we use more or less the same code as
previously. The only thing that needs to change is the SQL statement.
The steps are these:
1. Open a connection to MySQL
2. Specify the database we want to open
3. Set up a SQL Statement that can be used to add records to the
database table
4. Use mysql_query( ) again, but this time to add records to the table
5. Close the connection
To add records to the database, the INSERT statement is used.
There are plenty of ways to use this statement, but this example stick
with something simple: adding new values to all of our table columns.
<?PHP
$user_name = "root";
$password = "";
77
Php Programming Concepts and Database Driven Web Applications
$database = "addressbook";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "INSERT INTO tb_address_book (First_Name,
Surname, Address) VALUES ('bill', 'gates', 'Microsoft')";
$result = mysql_query($SQL);
mysql_close($db_handle);
print "Records added to the database";
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
4.7 Update/Delete a MySql record with PHP
• Update case: the SQL statement
The same steps are used as in the insert case, but at step 3 the
SQL statement is changed.
Example 1
$SQL = “UPDATE AddressBook SET email =
‘new_email_address’ WHERE First_Name = ‘Bill’ AND
Surname = ‘Gates’”;
Example 2
$SQL=“UPDATE
AddressBook
SET
Surname
=
LOWER(Surname)”;
Notice the WHERE clause. In example 1 we have specified that
the record to change should have the one where the First_Name is Bill
and the Surname is Gates; in example 2 the entire column (field) has
been updated: the build in SQL function LOWER( ) was used. This
changes a value to lower case letters. In between the round brackets of
the function, we have typed the column name again. This will ensure
that all the text in the Surname column gets changed to lower case.
78
Php Programming Concepts and Database Driven Web Applications
• Delete case: the SQL statement
Example 1
$SQL = “DELETE FROM AddressBook
First_Name = ‘Bill’ AND Surname = ‘Gates’”;
WHERE
An important note is that to make sure the WHERE clause is
going to be a unique value. In the code above, we might have more
than one Bill Gates in the table. If we do, everybody called Bill Gates
will be deleted! A better solution is to use a unique field from your
table, such as an ID field, as in example 2:
Example 2
$SQL = “DELETE FROM AddressBook WHERE ID = ‘7’”;
4.8 HTML – PHP – MySQL Creating Form Insert Data
Let’s consider a database named employees with a table named
data_employees with 3 fields (primary key, name and address).
The form input.html has three input fields because the table in the
database has three fields:
<html>
<head>
<title>Form Input Data</title>
</head>
<body>
79
Php Programming Concepts and Database Driven Web Applications
<table border="1">
<tr>
<td
align="center">Form
Input
Employees
Data</td>
</tr>
<tr>
<td>
<table>
<form method="post" action="input.php">
<tr>
<td>Name</td>
<td><input
type="text"
name="name"
size="20">
</td>
</tr>
<tr>
<td>Address</td>
<td><input
type="text"
name="address"
size="40">
</td>
</tr>
<tr>
<td></td>
<td align="right"><input type="submit"
name="submit" value="Sent"></td>
</tr>
</form>
</table>
</td>
</tr>
</table>
</body>
</html>
This html form will send two variables: $name and $address to
the input.php file as specified in the ACTION parameter of the form.
80