PHP Mini Guide
PHP Mini Guide
NeatInfo.com
/*
* multi-line
* comment
*/
Note: At the end of each PHP statement we need need to put a semicolon, i.e. ";"
as you see in the above code. Otherwise PHP will report syntax error.
A variable can only contain letters, numbers or underscore. In another words, you
can't use characters like <^# in your variables names.
<?php
$str = "I love PHP"; // variable with a string value
echo $str; // print the $str value onto the browser
Result: the browser should show "I Love PHP100I Love PHP100".
<?php
$integer_number = 100;
echo $number;
?>
<?php
$decimal_number = 100.01;
printf("%.2f", $decimal_number);
?>
<?php
$str = "I Love PHP";
echo $str
?>
Double quotes allow us to escape specials characters in our string. For example,
you can use a single quotes with in double quotes.
Special characters are escaped using backslash. Sometimes we need escape special
characters in our strings. We will learn about in the following section.
Jan Zumwalt – neatinfo.com Pg 7 of 55 rev April 1, 2010
Example - String in Double Quotes
<?php
$str = "It's a nice day today."
echo $str;
?>
or
<?php
$name = "Matt";
echo "Hello $name!";
?>
<?php
$str = "\"This is a PHP string examples in double quotes\"";
echo $str;
?>
<?php
$str = 'This is a PHP string examples in single quotes';
echo $str;
echo '<input type="text" name="first_name" id="first_name">';
?>
or
<?php
print '
<center><h1>Important</h1></center>
<p>This si a lot of html code<br />
that can be displayed using a<br />
single print statement and single<br />
quote</p>
' // end of print
?>
Single quotes allow double quotes in the string. Single quotes should be used when
outputting HTML code.
<?php
$str = 'It\'s a nice day today.';
echo $str;
?>
Sometimes while working with strings in our code, we need to join two strings. In
PHP, you can use '.' to concatenate two or more strings together to form a single
string.
<?php
$str1 = "I Love PHP.";
$str2 = "PHP is fun to learn.";
echo $str1." ".$str2;
?>
<?php
$str1 = "I Love PHP.";
$str2 = $str1." PHP is fun to learn.";
echo $str2;
?>
Result: 6.
<?php
$str = "Hello! How are you today?";
echo str_replace("Hello", "Hi", $str);
?>
<?php
$str = "hello!";
echo strtoupper($str);
?>
Result: "HELLO!"
<?php
$str = "hello!";
echo ucfirst($str);
?>
Result: "Hello!"
Result: "hello!"
or
if (condition1){
statement(s);
} else {
statement(s);
}
or
if (condition1){
statement(s);
} elseif (condition2){
statement(s);
}
or
if (condition1){
statement(s);
} elseif (condition2){
statement(s);
} else {
statement(s);
}
If there is only one line of code between the conditions, the brackets are not
needed.
<html>
<body>
<?php
//Give what day of the week it is. Returns Sunday through Saturday.
$day = date("l");
if ($day == "Saturday")
echo "It's party time :)";
else
echo "Ahhh! I hate work days.";
?>
</body>
</html>
<html>
<body>
<?php
//Give what day of the week it is. Returns Sunday through Saturday.
$day = date("l");
if ($day == "Saturday")
{
Jan Zumwalt – neatinfo.com Pg 11 of 55 rev April 1, 2010
echo "It's party time :)";
echo " Where are you going this evening?";
}
else
{
echo "Ahhh! I hate work days.";
echo " I want weekend to come :)";
}
?>
</body>
</html>
<html>
<body>
<?php
//Give what day of the week it is. Returns Sunday through Saturday.
$day = date("l");
if ($day == "Saturday")
{
echo "It's party time :)";
echo " Where are you going this evening?";
}
elseif ($day == "Friday")
{
echo "Have a nice day!";
}
else
{
echo "Ahhh! I hate work days.";
echo " I want weekend to come :)";
}
?>
</body>
</html>
<?php
?>
Note: The third increment statement can be set to increment by any number. In our
above example, we can set $i to increment by 2, i.e., $i=$i+2. In this case the
code will produce 0 2 4.
Example - Print table with alternate colors using PHP For Loop
You often seen tables cell with alternate colors on different websites. So, let
say we want to print the numbers in a table with alternate colors. This is how we
would do it.
<?php
echo "<table width='100' align='center'>";
0
for($i=0; $i<=5; $i=$i+1)
{ 1
if($i % 2 == 0) 2
{ 3
echo "<tr>";
echo "<td style='background-color:red'>"; 4
echo $i; 5
echo "</td>";
echo "</tr>";
}
else
{
echo "<tr>";
echo "<td style='background-color:green'>";
echo $i;
echo "</td>";
echo "</tr>";
}
}
echo "</table>";
?>
while(condition)
{
//execute block of code
}
<?php
$i = 1;
while ($i <= 5 )
{
echo $i . "<br>";
$i = $i + 1;
}
?>
Sometimes when we are working with loops, we want to break the loop when a certain
condition is true. We can use the break; statement to stop the loop from executing.
<?php
$i = 1;
while ($i <= 5 )
{
if($i == 4)
break;
echo $i . "<br>";
$i = $i + 1;
}
?>
• Numeric Arrays
• Associative Arrays
Numeric Arrays
There are two ways to create a numeric array. Lets look at each example to see how
we do that.
Result:
Lets extend our idea of associating a single key to an element. What if we want to
associate multiple keys to an element? Consider the Employees Table/Matrix below.
Employees Table/Matrix
Hmmm, that's nice but how the heck would I store employees table in an array?
Simple. PHP allows us to do that using multidimensional arrays. Let's look at the
examples below to see how we would do that.
Again, there are two ways to create a multidimensional array. Lets look at each
example to see how we do that.
The above code creates an multidimensional array name employees and outputs "Matt
is the Manager and he earns $40,000 a year.".
The above code creates an multidimensional array name employees and outputs "Dana
is the Owner and they earn $60,000 a year."
To print the results of an array you can use the PHP function print_r() to print
an array. See example below.
<?php
$employee_title["Dana"] = "Owner";
$employee_title["Matt"] = "Manager";
$employee_title["Susan"] = "Cashier";
echo "<pre>";
print_r($employee_title);
echo "</pre>";
?>
Array
(
[Dana] => Owner
[Matt] => Manager
[Susan] => Cashier
)
Note: Always remember to use <pre></pre> tags while printing an array as shown
above otherwise the result is not very reader friendly.
date(format[, timestamp])
<?php
echo date("Y-m-d"); // 2010-03-19
echo date("Y/m/d"); // 2010-03-19
echo date("M d, Y"); // Mar 19, 2010
echo date("F d, Y"); // March 19, 2010
echo date("D M d, Y"); // Fri Mar 19, 2010
echo date("l F d, Y"); // Friday March 19, 2010
echo date("l F d, Y, h:i:s"); // Friday March 19, 2010, 04:20:36
echo date("l F d, Y, h:i A"); // Friday March 19, 2010, 04:20 PM
?>
Where:
d - The day of the month, i.e. 01-31
m - Month representation in numbers, i.e. 01-12
Y - Year in four digits
<?php
echo "yesterday was ".date("Y-m-d", strtotime("-1 days"));
?>
<?php
echo "1 week from today was ".date("Y-m-d", strtotime("-1 weeks"));
?>
Result: 1 week from today was 2010-03-12
<?php
echo "1 month from today will be ".date("Y-m-d", strtotime("+1 months"));
?>
Result: 1 month form today will be 2010-04-19
mktime is used to find more specific things like the next leap year.
<?php
$day = "";
/*
* since leap year falls ever 4 years so loop for 4 times
*/
for($i=0; $i<4; $i++)
{
//get day timestamp for feburary 29 for this year
$day = date("d", mktime(0, 0, 0, 2, 29, date("Y")+$i));
/*
* check if day equals 29.
* If day is 29 then it must be the leap year. if day is 01, then it not a leap year.
*/
if($day == 29)
{
$year = date("Y")+$i;
break;
}
}
?>
Local File IO
fopen ($filename, $mode);
'r' Open for reading only; place the file pointer at the beginning of the file.
Open for reading and writing; place the file pointer at the beginning of the
'r+'
file.
Open for writing only; place the file pointer at the beginning of the file and
'w' truncate the file to zero length. If the file does not exist, it attempt to
create it.
Open for read/write; file pointer at beginning of file and truncate the file
'w+'
to zero length. If file does not exist, create it.
Open for write only; file pointer at the end of the file. If file does not
'a'
exist, create it.
<?php
$fh = fopen("myfile.txt", "r");
if($fh==false)
die("unable to create file");
?>
Result: Opens myfile.txt for reading and places the pointer at the beginning of
the files.
If the myfile.txt doesn't exist, the file handle $fh will return false. If you
like to create the file in case it doesn't exist, you can use the file mode 'a'.
This will create a new file myfile.txt, if it doesn't already exists.
<?php
$fh = fopen(" myfile.txt", "r+");
if($fh==false)
die("unable to create file");
?>
For that you can use file mode 'a' and 'a+' respectively to read/write from the
end of the file.
In this section we are going to cover how to open and read file content in PHP.
The fgets() functions is used to read a line from a file. Using this function we
either read the entire line into a string or specify the number characters we like
to read. Let’s looks at the function more closely...
The fgets() function has two parameter. The first parameter is the file pointer
and the 2nd parameter which is optional is the number of bytes to read in one
call. If the 2nd parameter is not giving, the function will read at the end of the
line.
The following code reads a line from a file into a string. The code will start off
by placing the file pointer at the beginning of the file and then reading the
first line in our file into a string.
<?php
$fh = fopen("myfile.txt", "r");
$line = fgets($fh);
echo $line;
fclose($fh);
?>
In the above we didn't specify how many bytes we want to read. Therefore, the
entire line is read.
Remember, the mode 'r' means we are opening the file for reading only.
In this second example, we use the same method to read only certain number of
characters in a line.
<?php
$fh = fopen("myfile.txt", "r");
fclose($fh);
?>
The above code reads the first 64 characters and then reads the next 64 characters
in the line.
Using the fgets() function we can also read the entire file line by line in one
loop. Let's look at two different examples to see how we can do that.
<?php
$fh = fopen("myfile.txt", "r");
while(true)
{
$line = fgets($fh);
if($line == null)break;
echo $line;
}
fclose($fh);
?>
<?php
$fh = fopen("myfile.txt", "r");
while (!feof($fh)) {
$line = fgets($fh);
echo $line;
}
fclose($fh);
?>
In some cases you might need to read the entire file at once. Reading the file
line by line is probably more work in that case.
In this case you can utilize other functions that will read the entire file
content in a string in one go. Once such function is file_get_contents()
<?php
$fh = fopen("myfile.txt", "r");
$file = file_get_contents("myfile.txt");
echo $file;
?>
The above code will read the entire file content of myfile.txt into the string
$file.
Please note that if the file is fairly large, your script/application might hang
due to lack of resources. It is not advisable to read big files in one go. Either
you should split the file into two or more pieces or utilize more smart ways of
reading a file.
Writing text to files is fairly easy in PHP. We can easily write text to files
using the fwrite() function. However, you must make sure to open file in writable
mode before writing. You will see which modes to use when writing to files and how
to write to files in examples below.
The fwrite() function takes three arguments, the file handle, the string to be
written and the number of bytes to be written, which is optional.
Now, let's work with some examples below on how to write text to files.
The first example demonstrates how to write a single line of text to a file.
<?php
$handle = fopen("myfile.txt", 'w+');
if($handle)
{
?>
<pre>
The above code creates a new file myfile.txt in writable mode using "w+" and
writes "Student Name: Mark Fendisen" into the file.
Note: "w+" truncates the file to zero, that is, deletes everything in the file
before writing. If the file doesn't exists, it create a new file.
Using file open mode "a+", you can append text to either beginning or end of a
file. We will see how we can do in the examples below
The first example we tackle is, how to write text at the beginning of a file.
The first thing we need to do is open the file in append mode using 'a+'. In other
words, open an existing file so that we can add more stuff to it.
The code below writes the string "Student ID: 12345" in the beginning without
truncating the file, which means that anything already in the file is left alone,
and the new string in written in the beginning of the file.
When you open a file with mode 'a+', the file pointer is placed at the end of the
file but remember we want to write at the beginning of the file. To move the file
pointer back to the beginning for writing, we can use the function rewind() as
seen below.
<?php
$file_name= "myfile.txt";
if(file_exists($file_name))
{
//open file for writng and place pointer at the end
$handle = fopen($file_name, 'a+');
if(!$handle)
{
die("couldn't open file <i>$file_name</i>");
}
//write to file
As seen in the above example, the mode "a+" automatically places the file pointer
at the end of the file so we don't have to do anything extra in this case.
The code below writes "Student GPA: 2.9" at the end of the file.
<?php
$file_name= "myfile.txt";
if(file_exists($file_name))
{
//open file for writng and place pointer at the end
$handle = fopen($file_name, 'a+');
if(!$handle)
{
die("couldn't open file <i>$file_name</i>");
}
The examples you saw so far write text in one straight line. What if we want line
breaks?
Well, we can write text one per line in a file by using carriage return, '\n' or
'\r'.
If you are using PC, use "\n". For Macintosh, use "\r". But just to be on the safe
side, you can use both together like this "\r\n" regardless of what system you're
running your code on. This will guarantee it works under both PCs and Macintosh.
<?php
$file_name = "myfile.txt";
if(file_exists($file_name))
{
//open file for writng and place pointer at the end
$handle = fopen($file_name, 'w');
if(!$handle)
{
die("couldn't open file <i>$file_name</i>");
}
$str.= "Student Name: Mark Fendisen\r\n";
$str.= "Student ID: 12345\r\n";
Jan Zumwalt – neatinfo.com Pg 24 of 55 rev April 1, 2010
$str.= "Student GPA: 2.9\r\n";
fwrite($handle, $str);
echo "success writing to file";
}
else
{
echo "file <i>$file_name</i> doesn't exists";
}
fclose($handle);
?>
Most often you will find yourself reading and writing to a file at the same time.
The example below shows you how to parse data in a file, i.e. read file line by
line and overwrite small part of text in a file with new string.
For our example below we will assume we have file which contains the following
information about a student.
What we want to do is update his GPA from 2.9 from 3.1. How would we do it?
First we need to open the file in both read and write mode using "r+". Next, we
read the file line by line using fgets function until we reach the student gpa
line. We then use string replace function to replace 2.9 with 3.1 and write the
new string back to the file.
With me? That's okay if you're not :) Let's examine the code below and you will
understand what we have done.
<?php
$file_name= "myfile.txt";
if(file_exists($file_name))
{
/* Open file for both reading and writng.
* Place pointer at the beginning of the file.
*/
$handle = fopen($file_name, 'r+');
if(!$handle)
{
die("couldn't open file <i>$file_name</i>");
}
while(1)
{
//read line
$line = fgets($handle);
//if end of file reached then stop reading anymore
if($line == null)break;
Result:
The above code is fairly large. I would recommend to go over it slowly and read
the internal comments in the code to understand how it is done.
where:
$hostname - location or URL of the file or page.
$port - the default port is 80, unless otherwise told.
$errno - optional, contains error number during connection.
$errstr - optional. contains error message during connection
$timeout - optional. seconds before connection timeout error.
The example below shows how to read the source code of a page and display it.
<?php
$fp = fsockopen("www.somedomain.com", 80, $errno, $errstr, 30);
if ($fp == false) {
echo "$errstr ($errno)";
} else {
while (!feof($fp)) {
echo fgets($fp, 1024);
}
fclose($fp);
}
?>
So, in this tutorial we learned how to open files for reading and writing. In the
next tutorial, we will cover how to read from files and how to write to files.
<html>
<head><title>Simple php form visitor_form.php</title></head>
<body>
<?php
print '
<form method="post" action="visitor_info.php">Your Name: <br />
<input type="text" name="visitorname" size="35" />
<br /><br />
Your Email:<br />
<input type="text" name="visitormail" size="35" />
<br /> <br />
Age:<br />
<select name="visitorage" size="1">
<option value="0-10">0-10</option>
<option value="11-25">11-25</option>
<option value="26-50">26-50</option>
<option value="50+">over 50</option>
</select>
<br /><br />
<input type="submit" value="Send Info" />
<br />
</form>
' // end of print
?>
</body>
</html>
<html>
<head>
<head><title>Simple php form visitor_info.php</title></head>
</head>
<body>
<h1> PHP simple form processing </h1>
<?php
$vname = $_POST['visitorname'];
$vmail = $_POST['visitormail'];
$vage = $_POST['visitorage'];
$todayis = date("l, F j, Y, g:i a");
print "Today's date: $todayis<br />";
print "You name: $vname<br />";
print "Your email: $vmail<br />";
print "Your age: $vage<br />";
?>
<br />
<a href="visitor_form.php"> back to form </a>
</body>
</html>
The following code will send out a plain text email using the PHP built in mail
function.
<?php
function send_email($from, $to, $cc, $bcc, $subject, $message){
$headers = "From: ".$from."\r\n";
$headers .= "Reply-To: ".$from."\r\n";
$headers .= "Return-Path: ".$from."\r\n";
$headers .= "CC: ".$cc."\r\n";
$headers .= "BCC: ".$to."\r\n";
if (mail($to,$subject,$message,$headers) ) {
echo "email sent";
} else {
echo "email could not be sent";
}
}
$subject = "Hello!";
$message = "Hello! How are you today?";
send_email("[email protected]", "[email protected]",
"[email protected]", "[email protected]",
$subject ,
$message);
?>
In our send_email function we set the appropriate headers. Reply-To and Return-
Path points to the email you want the recipient to reply to. Some server requires
the use of Return-Path, so it's good to leave it in there.
Next we call the send_email function which sends out the email.
The following function will send out an HTML formatted email using the PHP built
in mail function.
<?php
function send_email($from, $to, $subject, $message){
$headers = "From: ".$from."\r\n";
$headers .= "Reply-To: ".$from."\r\n";
$headers .= "Return-Path: ".$from."\r\n";
$headers .= "Content-type: text/html\r\n";
if (mail($to,$subject,$message,$headers) ) {
echo "email sent";
} else {
Jan Zumwalt – neatinfo.com Pg 29 of 55 rev April 1, 2010
echo "email couldn't be sent";
}
}
$subject = "Helloooo!";
$message .= "<html><body>";
$message .= "<b>Hey! How are you today?</b>";
$message .= "<br>Regards";
$message .= "</body></html>";
send_email("[email protected]", "[email protected]",
$subject ,
$message);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Email Form </title>
</head>
<body>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sendemail Script</title>
</head>
<body>
<!-- Reminder: Add the link for the 'next page' (at the bottom) -->
<!-- Reminder: Change 'YourEmail' to Your real email -->
<?php
$ip = $_POST['ip'];
$httpref = $_POST['httpref'];
$httpagent = $_POST['httpagent'];
$visitor = $_POST['visitor'];
$visitormail = $_POST['visitormail'];
$notes = $_POST['notes'];
$attn = $_POST['attn'];
if (eregi('http:', $notes)) {
die ("Do NOT try that! ! ");
}
if(!$visitormail == "" && (!strstr($visitormail,"@") || !strstr($visitormail,".")))
{
echo "<h2>Use Back - Enter valid e-mail</h2>\n";
$badinput = "<h2>Feedback was NOT submitted</h2>\n";
echo $badinput;
die ("Go back! ! ");
}
$attn = $attn ;
$subject = $attn;
$notes = stripcslashes($notes);
<p align="center">
Date: <?php echo $todayis ?>
<br />
Thank You : <?php echo $visitor ?> ( <?php echo $visitormail ?> )
<br />
Jan Zumwalt – neatinfo.com Pg 31 of 55 rev April 1, 2010
Attention: <?php echo $attn ?>
<br />
Message:<br />
<?php $notesout = str_replace("\r", "<br/>", $notes);
echo $notesout; ?>
<br />
<?php echo $ip ?>
</body>
</html>
<?php
session_start();
?>
<html>
<body>
</body>
</html>
When you start a session a unique session id (PHPSESSID) for each visitor/user is
created. You can access the session id using the PHP predefined constant
PHPSESSID.
The code above starts a session for the user on the server, and assign a session
id for that user's session.
Note: The session_start() function must appear BEFORE the <html> tag
To store information is a session variable, you must use the predefined session
variable $_SESSION.
<?php
session_start();
$_SESSION["username"] = "johny";
$_SESSION["color"] = "blue";
?>
Retrieving stored session information is really easy. You can access the stored
session information on any page without doing anything extra.
<?php
session_start();
echo $_SESSION["username"];
echo "<br/>";
echo $_SESSION["color"];
?>
Result:
Johny
blue
Remember sessions are destroyed automatically after user leaves your website or
closes the browser, but if you wish to clear a session variable yourself, you can
simple use the unset() function to clean the session variable.
<?php
session_start();
unset($_SESSION["username"]);
unset($_SESSION["color"]);
?>
To completely destroy all session variables in one go, you can use the
session_destroy() function.
<?php
session_destroy();
?>
<?php
setcookie("username", "john", time()+3600);
?>
<html>
<body>
</body>
</html>
Cookie username is set with value john which is set to expire after one hour on
users computer.
The function time() retrieves the current timestamp. Appending 3600 seconds (one
hour) to the current time to make the cookie to expire after one hour.
Note: A cookie must be set before any HTML code as shown above.
<?php
setcookie("username", "john", time()+(60*60*24*365));
?>
Retrieving a cookie
Cookie information is retrieved using the predefined $_COOKIE array. The following
will retrieve our username cookie value
Jan Zumwalt – neatinfo.com Pg 35 of 55 rev April 1, 2010
<?php
echo $_COOKIE["username"];
?>
Result:
john
<?php
echo "<pre>";
print_r($_COOKIE);
echo "</pre>";
?>
Result:
Array
(
[username] => john
)
Deleting a Cookie
In order to delete cookies, you just set the cookie to expire in the past date.
<?php
setcookie("username", "john", time()-(60*60*24*365));
?>
There is a simple test for both PHP and MySQL. Open a text editor and type in the following:
<?
phpinfo();
?>
Database Construction
MySQL databases have a standard setup. They are made up of a database, in which is contained
tables. Each of these tables is quite separate and can have different fields etc. even though it is part
of one database. Each table contains records which are made up of fields.
The process of setting up a MySQL database varies from host to host, you will however end up with a
database name, a user name and a password. This information will be required to log in to the
database.
If you have PHPMyAdmin (or a similar program) installed you can just go to it to log in with your user
name and password. If not you must do all your database administration using PHP scripts.
Creating A Table
Before you can do anything with your database, you must create a table. A table is a section of the
database for storing related information. In a table you will set up the different fields which will be used
in that table. Because of this construction, nearly all of a site's database needs can be satisfied using
just one database.
Creating a table in PHPMyAdmin is simple, just type the name, select the number of fields and click
the button. You will then be taken to a setup screen where you must create the fields for the
database. If you are using a PHP script to create your database, the whole creation and setup will be
done in one command.
Fields
There are a wide variety of fields and attributes available in MySQL and I will cover a few of these
here:
These are just a few of the fields which are available. A search on the internet
will provide lists of all the field types allowed.
To create a table in PHP is slightly more difficult than with MySQL. It takes the
following format:
Jan Zumwalt – neatinfo.com Pg 38 of 55 rev April 1, 2010
CREATE TABLE tablename {
Fields
}
The final field entered should not have a comma after it.
The contacts database will contain all the conact information for the people you
enter and the information will be able to be edited and viewed on the internet.
The following fields will be used in the database:
You may be wondering why I have used VARCHAR fields for the phone/fax numbers even
though they are made up of digits. You could use INT fields but I prefer to use
VARCHAR as it will allow dashes and spaces in the number, as well as textual
numbers (like 1800-COMPANY) and as we will not be initiating phone calls from the
web it is not a problem.
There is one other thing you should be aware of in this database. The id field
will also be set as PRIMARY, INDEX, UNIQUE and will be set to auto_increment
(found under Extra in PH
PMyAdmin). The reason for this is that this will be the field identifier (primary
and index) and so must be unique. The auto increment setting means that whenever
you add a record, as long as you don't specify an id, it will be given the next
number.
If you are using PHPMyAdmin or a management program you can now create this in a
table called contacts.
The following code should be used to create this table in PHP. Some of the code
has not been covered yet but I will explain it fully in the next part.
<?
$user="username";
$password="password";
$database="database";
mysql_connect(localhost,$user,$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
Jan Zumwalt – neatinfo.com Pg 39 of 55 rev April 1, 2010
(id),UNIQUE id (id),KEY id_2 (id))";
mysql_query($query);
mysql_close();
?>
Enter your database, MySQL username and MySQL password in the appropriate
positions on the first three lines above.
Over the past two parts I have explained what I am planning to do in this tutorial
and have shown you how to create a database to use with the tutorial. In this part
I will be showing you how to insert some information into your database so that it
is more useful.
The first thing you must do before you can do any work at all is to connect to the
MySQL database. This is an extremely important step as, if you are not connected,
your commands to the database will fail.
Good practice for using databases is to specify the username, password and
database name first so that if you change any of them at a later date you will
only have to change one line:
$username="username";
$password="password";
$database="your_database";
At this point you may be wondering if it is a security risk, keeping your password
in the file. You don't need to worry, though, because the PHP scource code is
processed aby the server before being sent to the browser so it is impossible for
the user to see the script's source.
Next, you will need to issue the command to start a database connection:
mysql_connect(localhost,$username,$password);
This line tells PHP to connect to the MySQL database server at 'localhost'
(localhost means the server that the site is running one. Unless you web host
tells you otherwise you should use localhost. If you are given a server address
(such as sql.myserver.com you should replace localhost with "sql.myserver.com"
(including the quotes)) using the username stored in $username and the password in
$password.
Before I show you how to work with the database, I will show you one more command:
mysql_close();
After you have connected to the database server you must then select the database
you wish to use. This must be a database to which your username has access. The
following command:
is used to do this. This tells PHP to select the database stored in the variable
$database (which you set earlier). If it cannot connect it will stop executing the
script and output the text:
This extra 'or die' part is good to leave in as it provides a little error control
Jan Zumwalt – neatinfo.com Pg 41 of 55 rev April 1, 2010
but it is not essential.
Executing Commands
Now you have connected to the server and selected the database you want to work
with you can begin executing commands on the server.
There are two ways of executing a command. One is to just enter the command in
PHP. This way is used if there will be no results from the operation.
The other way is to define the command as a variable. This will set the variable
with the results of the operation.
In this part of the tutorial we will use the first way as we are not expecting a
response from the database. The command will look like this:
mysql_query($query);
The useful thing about using this form of the command is that you can just repeat
the same command over and over again without learning new ones. All you need to do
is to change the variable.
Inserting Data
For this part of the tutorial I will return to the contacts database which we
created in the last part. We will now add our first information to the database:
First: John
Last: Smith
Phone: 01234 567890
Mobile: 00112 334455
Fax: 01234 567891
E-mail: [email protected]
Web: http://www.gowansnet.com
This may look a little confusing at first so I will explain what it all means.
Firstly $query= is there because we are assigning this to the variable $query (see
the section above). The next part:
is quite easy to understand. It tells the PHP to insert into the table called
contacts the values in the brackets which follow.
The part in the brackets contains all the information to add. It uses all the
fields in order and inserts the information from between the quotes. For example:
John
will be inserted into the 2nd field which, in this table, is the 'first' field.
You may have noticed that you are not inserting any value into the first field in
the database (id). This is because this field is going to act as an index field.
No two records in the database will have the same ID. Because of this, when we set
up the database we set ID to 'Auto Increment'. This means that if you assign it no
value it will take the next number in the series. This means that this first
record will have the ID 1.
So far in this tutorial, you have created a database and put information into it.
In this part I will show you how to create an input page for your database, and
how to display the whole contents.
HTML Input
Inputing the data using HTML pages is almost identical to inserting it using a PHP
script. The benefit, though, is that you do not need to change the script for each
piece of data you want to input and you can also allow your users to input their
own data.
The following code will show an HTML page with textboxes to enter the appropriate
details:
This page could, of course, be formatted and have other changes made to it. It is
just a basic form to get you started. Next you will need to edit the script from
last week. Instead of using information to input into the database, you will
instead use variables:
<?
$username="username";
$password="password";
$database="your_database";
$first=$_POST['first'];
$last=$_POST['last'];
$phone=$_POST['phone'];
$mobile=$_POST['mobile'];
$fax=$_POST['fax'];
$email=$_POST['email'];
$web=$_POST['web'];
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
mysql_close();
?>
This script should then be saved as insert.php so that it can be called by the
HTML form. It works because, instead of the data being entered locally, it is
being entered into the form and stored in variables which are then passed to the
PHP.
You could also add to this script a message confirming the data input. This is
basic PHP, though, and you should read the PHP tutorial if you do not know how to
do this.
Outputting Data
The first command you will need to use is a MySQL query made up like this:
This is a basic MySQL command which will tell the script to select all the records
in the contacts table. Because there will be output from this command it must be
executed with the results being assigned to a variable:
In this case the whole contents of the database is now contained in a special
array with the name $result. Before you can output this data you must change each
piece into a separate variable. There are two stages to this.
Counting Rows
Before you can go through the data in your result variable, you must know how many
database rows there are. You could, of course, just type this into your code but
it is not a very good solution as the whole script would need to be changed every
time a new row was added. Instead you can use the command:
$num=mysql_numrows($result);
This will set the value of $num to be the number of rows stored in $result (the
output you got from the database). This can then be used in a loop to get all the
data and output it on the screen.
nYou must now set up a loop to take each row of the result and print out the data
held there. By using $num, which you created above, you can loop through all the
rows quite easily. In the code below, $i is the number of times the loop has run
and is used to make sure the loop stops at the end of the results so there are no
errors.
$i=0;
while ($i < $num) {
CODE
$i++;
}
This is a basic PHP loop and will execute the code the correct number of times.
Each time $i will be one greater than the time before. This is useful, as $i can
be used to tell the script which line of the results should be read. As the first
line in MySQL output is 0, this will work correctly.
The final part of this output script is to assign each piece of data to its own
variable. The following code is used to do this:
$variable=mysql_result($result,$i,"fieldname");
So to take each individual piece of data in our database we would use the
$first=mysql_result($result,$i,"first");
$last=mysql_result($result,$i,"last");
$phone=mysql_result($result,$i,"phone");
$mobile=mysql_result($result,$i,"mobile");
$fax=mysql_result($result,$i,"fax");
$email=mysql_result($result,$i,"email");
$web=mysql_result($result,$i,"web");
We do not need to get the ID field (although we could have done) because we have
no use for it in the current output page.
We can now write a full script to output the data. In this script the data is not
formatted when it is output:
<?
$username="username";
$password="password";
$database="your_database";
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM contacts";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
$i=0;
while ($i < $num) {
$first=mysql_result($result,$i,"first");
$last=mysql_result($result,$i,"last");
$phone=mysql_result($result,$i,"phone");
$mobile=mysql_result($result,$i,"mobile");
$fax=mysql_result($result,$i,"fax");
$email=mysql_result($result,$i,"email");
$web=mysql_result($result,$i,"web");
$i++;
}
?>
Throughout this tutorial you have learnt how to create a database and table,
insert information and display the database information. In this part I will show
you more ways of displaying and outputting the information in the database.
Formatting Output
In the last part of the tutorial we output a list of all the people stored in the
database. This just gave us a very basic output, though and is not particularly
useful for a working website. Instead, it would be better if we could format it
into a table and display it like this.
Doing this formatting is not particularly complicated. All you need to do is use
PHP to output HTML and include your variables in the correct spaces. The easiest
way to do this is by closing your PHP tag and entering the HTML normally. When you
reach a variable position, include it as follows:
You can also use the PHP loop to repeat the appropriate code and include it as
part of a larger table. For example, using a section of the code from part 4 which
looped to output the database you can format it to display it in one large table:
<?
$i=0;
while ($i < $num) {
$first=mysql_result($result,$i,"first");
$last=mysql_result($result,$i,"last");
$phone=mysql_result($result,$i,"phone");
$mobile=mysql_result($result,$i,"mobile");
$fax=mysql_result($result,$i,"fax");
$email=mysql_result($result,$i,"email");
$web=mysql_result($result,$i,"web");
?>
<tr>
<td><font face="Arial, Helvetica, sans-serif"><? echo $first." ".$last; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><? echo $phone; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><? echo $mobile; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><? echo $fax; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><a href="mailto:<? echo $email; ?>">E-
mail</a></font></td>
<td><font face="Arial, Helvetica, sans-serif"><a href="<? echo $web;
?>">Website</a></font></td>
</tr>
<?
$i++;
}
This code will print out table headers, then add an extra row for each record in
the database, formatting the data as it is output.
As long as you are familiar with PHP and HTML the code is probably pretty self
explanatory but I will just point out the last two lines in the table, for
example:
This shows one of the useful features of using PHP to include MySQL data as you
can use it to output parts of your code and make pages fully dynamic.
As well as showing the whole database, PHP can be used to select individual
records, or records which match certian criteria. To do this you must use a
variation of the SELECT query. To display the whole table we used the query:
If we just wanted to select ones who had the first name 'John' you would use the
following query:
As with other MySQL queries, it is almost like plain english. In the same way you
could select records based on any field in the database. You can also select ones
with more than one field by adding more:
field='value'
Please note that at the end of the first line there is a ' followed by a " before
the semicolon.
Security
At this point it should be noted that you must be very careful in using the
technique given above. Without correct secuirty measures, it would be very easy
for someone to access data on your server, or even make changes to the database.
This can occur if the user sets the variable to a value which edits the SQL string
being generated in such a way that it can be used for their own purposes. I won't
go into full details here, but there are many websites which give full details
(search for 'sql injection attack').
This security hole is easy to plug with a bit of work. Always check input data for
invalid chanracters and use PHP's built in functions to remove control characters
and HTML code etc. Again, there are many websites which go into this in depth.
In the past two parts of this tutorial I have shown you how to take data out of
the database and display it on screen. In this part I will enter into the final
aspect of this data displaying, selecting one piece of data and stopping errors
from happening when you output data.
Error Trapping
By outputting all the information from the database, it is quite unlikely that
there will be no data, but if you allow updating and deleting of records, it is
certainly a possibility. Luckily, with PHP and MySQL, there is an easy way round
this using:
$num=mysql_numrows($result);
where $result contains the result of a query on the database (like selecting all
the records). As I expalined before, this will set the value of $num as the number
of rows in the result (and it was used in a loop in part 4). Because of this you
can make a simple error trap using an IF statement:
if ($num==0) {
echo "The database contains no contacts yet";
} else {
Output Loop
}
You can expand on this more by making it more user friendly (for example by
providing a link to the Add Data page if no contacts exist).
Ordering Data
Not only can you output data based on the contents of a field, but you can also
order the output based on a field (for example placing users in alphabetical
order). By default, the output from your queries will be in order of the id field,
going from 1 upwards. You can sort it on any field, though.
For example, a useful sort would be to place all the users in alphabetical order
based on their last name. For those not familiar with standard databases, this
would be in Ascending order as it goes from A to Z. (Ascending order is also for
1-10 etc. and descending order provides Z to A and 10-1). To do this you would use
the following query:
You could also use DESC to order the data in Descending order.
The value you have assigned to $num is very imiportant as, apart from error
trapping and loops, it has many other uses. An example of this would be to print
out only the last 5 records added to a database. Firstly, they would need to be
placed into order based on the id field (as the one with the latest ID would have
been added last. This would require them to be in Descending order.
Now you have them in order of newest to oldest but this does not restrict the
script to only showing the first 5. To do this, you would need to set your loop to
run to 5 instead of $num (as this would only run the loop 5 times so only 5
records would be output).
Of course, before doing this, it would be important to check that $num was greater
if ($num>5) {
$to=5;
}else{
$to=$num;
}
$i=0;
while ($i < $to) {
REST OF CODE
This code would check if there were more than 5 rows in the database. If there
were, the loop would be set to run 5 times. If there were less than 5 rows the
loop would run the correct number of times to output the whole database.
The ID Field
If you remember back to creating the database for the contacts at the beginning of
this tutorial, you will remember that we included a numerical field called id.
This field was set as auto_increment as well as being the primary field. I have
already explained how this field is unique for every single record in the
database, but I will now take this a stage further by explaining how this can be
used to select an individual record from a database.
Now, by using the unique ID field we can select any record from our database
using:
Where $id is a variable holding a number of a record. This may seem to be a little
worthless as it is, but you can use this very effectively in a number of different
ways. For example, if you wanted to have a dynamically generated site run through
a database and a single PHP script, you could write the script to include the
database data into the design. Then, using the id field, you could select each
individual page and put it into the output. You can even use the page's URL to
specify the record you want e.g.
http://www.yoursite.com/news/items.php?item=7393
And then have the PHP script look up the record with the id corresponding to
$item, which in this case would be 7393
Using this method of choosing a record using the URL to select the record can be
expanded further by generating the URL dynamically. This sounds a bit complicated
so I will elaborate. In the contacts script we are writing, I will be showing you
how to create an Update page where the user can update the contact details.
To do this, another column will be included in the output column, with an Update
link in it. This update link will point to a page allowing the user to update the
record. To select the record in this page, we will put:
By getting the id of the record along with the other information when we are
outputting the information from the database, this code will create a link which
has each record's ID number in it. Then, on the update page, there can be code to
just select this item.
So far you have learnt how to put information into your MySQL database, view the
information in it and select which information you would like to view. In this
part I will show you how to do the two final actions, updating your database and
deleting records from it.
Last week I explained how to create a link for each record to point to your update
script. By using the $id variable you output links which would pass the correct ID
to the script so that it can update the database. Using this you can then create
the update script, which will actually have two sections to it.
The first part of the update script uses the single record selection from last
week but adds a little HTML to it to make it more useful. First of all, we connect
to the database and select the appropriate record.
$id=$_GET['id'];
$username="username";
$password="password";
$database="your_database";
mysql_connect(localhost,$username,$password);
$i=0;
while ($i < $num) {
$first=mysql_result($result,$i,"first");
$last=mysql_result($result,$i,"last");
$phone=mysql_result($result,$i,"phone");
$mobile=mysql_result($result,$i,"mobile");
$fax=mysql_result($result,$i,"fax");
$email=mysql_result($result,$i,"email");
$web=mysql_result($result,$i,"web");
++$i;
}
Where 'Space For Code' is in this script is where the code for the update page
will go. This is, in fact, just HTML formatting for the output:
As you can see, this code will output a standard form, but instead of having blank
boxes like on the form for inserting a new record, this one already has the
current information from the database inserted into it. This makes it much more
The next stage of this script is to actually update the database. This is a simple
operation and just involves a new query for the database:
$query = "UPDATE contacts SET first = '$ud_first', last = '$ud_last', phone = '$ud_phone',
mobile = '$ud_mobile', fax = '$ud_fax', email = '$ud_email', web = '$ud_web' WHERE id =
'$ud_id'";
This query tells the database to update the contacts table where the ID is the
same as the value stored in $ud_id (which as you can see from the form on the
previous page was set as the id of the record we are updating) and to set the
following fields to the specified values (which were set using the form on the
previous page).
$ud_id=$_POST['ud_id'];
$ud_first=$_POST['ud_first'];
$ud_last=$_POST['ud_last'];
$ud_phone=$_POST['ud_phone'];
$ud_mobile=$_POST['ud_mobile'];
$ud_fax=$_POST['ud_fax'];
$ud_email=$_POST['ud_email'];
$ud_web=$_POST['ud_web'];
$username="username";
$password="password";
$database="your_database";
mysql_connect(localhost,$username,$password);
This code would update the database and give the user a confirmation.
Deleting Records
The final part of the contacts database which needs to be created is a page to
delete records. As with the Update page, this should have a record ID sent to it
in the URL e.g.:
delete.php?id=9
The code to do this is the same as to update the database, except with a slightly
different MySQL query. Instead of the UPDATE query you should use:
This would then be used with the connection and confirmation code as above.
Loops
At this time it seems appropriate to mention another use of loops with a database.
As well as using a loop to get information from a database as we have before, you
can also use loops to execute queries. For example, if you wanted to change all
the records in the database with the last name Smith to have the website
www.smith.com:
$i=0;
while ($i < $num) {
$id=mysql_result($result,$i,"id");
$query1="UPDATE contacts SET web='http://www.smith.com' WHERE id='$id'";
mysql_query($query);
++$i;
}
mysql_close();
Of course, this could have been achived far easier and quicker using:
and no loop.
Throughout this tutorial I have taught you how to use PHP to interact with a MySQL
(or SQL) database and how to use the most common commands available. I have,
throughout this tutorial, also shown you how to create a basic contacts management
system to illustrate some of the options you can use. In this part I will show you
some final MySQL tips and will give you a final version of the script.
Saving Time
When creating complex scripts using databases you will find that the most common
thing you are doing is connecting to a database. Because of this, you can actually
save time by creating either a username/password file or a connection file. For
example for a username/password file you would create a file called:
dbinfo.inc.php
<?
$username="databaseusername";
$password="databasepassword";
$database="databasename";
?>
Replacing the appropriate sections. Then in your php files use the following code:
include("dbinfo.inc.php");
or
include("/full/path/to/file/dbinfo.inc.php");
at the beginning. Then, you can use the variables $username, $password and
$database throughout your scripts without having to define them every time. Also,
if you ever change this information, for example if you move to another web host,
there is only one file to change.
You can use the same principal to connect to the database, by putting the
connection code in the file, but you must always be sure to close the connection
in each file or you may have problems with your MySQL server.
Searching
A limited form of searching can also be performed on your database using a built
in MySQL function. This is by using the LIKE function as follows:
To explain furhter, LIKE tells the database to perform its 'searching' feature.
The % signs mean that any other data could appear in their place and $string would
hold your search string. In this place could be a word or number as well e.g.:
LIKE '%piano%'
which would output any rows with piano in the specified field.
Similarly, you can leave out one of the % signs so that you can specify the
position of the string e.g.:
LIKE 'piano%'
Throughout this tutorial I have given you pieces of code to make a contacts
database script. You can download the full script as a zip file so that you can
examine the code (see Related Links).
Conclusion
From this tutorial you should now know the basics of using PHP and MySQL together
to create database-enabled websites and programs. Using databases with the web
opens up a huge new selection of things you can do and can make a simple website
much more powerful, saving time updating the site, allowing user interaction and
feedback and much more.