You are on page 1of 23

c 


PHP is a server side scripting language used on the Internet to create dynamic web
pages. It is often coupled with MySQL, a relational database server that can store the
information and variables the PHP files may use. Together they can create everything
from the simplest web site to a full blown business web site, an interactive web forum,
or even an online role playing game.

Learn more about PHP.

Before we can do the big fancy stuff we must first learn the basics from which we build
on.

1.| Start by creating a blank file using any program that can save in plain text
format.
2.|      , for example mypage.php. Saving a page with the
.php extension tells your server that it will need to execute the PHP code.
3.| nter the statement ¦  to let the server know that there is PHP code coming
up.
4.| ëfter this we would enter the body of our PHP program.
5.| nter the statement  to let the browser know the PHP code is done.

very section of PHP code starts and ends by turning on and off PHP tags to let the
server know that it needs to execute the PHP in between them. Here is an example:

¦  //on

//and

//off 

verything between the <?php and ?> is read as PHP code. The ¦  statement can
also be phrased as simply ¦ if desired. ënything outside of these PHP tags is read as
HTML, so you can easily switch between PHP and HTML as needed. This will come in
handy later in our lessons.



If you want something to be ignored (a comment for example) you can put // before it as
I did in our example on the previous page. There are a few other ways of creating
comments within PHP, which I will demonstrate below:
<?php

//ë comment on a single line

#ënother single line comment

/*
Using this method
you can create a larger block of text
and it will all be commented out
*/

?>

One reason you may want to put a comment in your code is to make a note to yourself
about what the code is doing for reference when you edit it later. You may also want to
put comments in your code if you plan on sharing it with others and want them to
understand what it does, or to include your name and terms of use within the script.

 



First we are going to learn about the echo statement, the most basic statement in PHP.
What this does is output whatever you tell it to echo. For example:
<?php echo "I like ëbout" ?>

This would return the statement á   . Notice when we echo a statement, it is
contained within quotation marks [⼜â¼*.

ënother way to do this is to use the print function. ën example of that would be:

<?php print "I like ëbout" ?>

There is a lot of debate about which is better to use or if there is any difference at all.
ëpparently in very large programs that are simply outputting text the  statement
will run slightly faster, but for the purposes of a beginner they are interchangeable.

ënother thing to keep in mind is that all of your print/echoing is contained between
quotation marks. If you want to use a quotation mark inside of the code, you must use a
backslash:

<?php print "Billy said I like ëbout too" ?>


When you are using more than one line of code inside your php tags, you must separate
each line with a semicolon [;*. Below is an example of printing multiple lines of PHP,
right inside your HTML:
<html>
<head>
<title>PHP Test Page</title>
</head>
<body>
<center><b>
<?php
print "I like ëbout";
print "<br>";
print "Billy said \"I like ëbout too\""
?>
</b></center>
</body>
</html>

ës you can see, you can insert HTML right into your php print line. You can format the
HTML in the rest of the document as you please, but    
 
  
 

   
The next basic thing you need to learn how to do is to set a variable. ë variable is
something that represents another value.
<?php
$like = "I like ëbout";
print $like;
$num = 12345;
print $num;
?>

This sets our variable, $like, to our previous á   statement. Notice again the
quotation marks [⼜â¼* used, as well as the semicolon [;* to show the end of the
statement. The second variable $num is an integer, and therefore does not use the
quotation marks. The next line prints out the variable $like and $num respectively. You
can print more than one variable on a line using a period [.*, for example:

<?php
$like = "I like ëbout";
$num = 12345;
print $like . $num;
print "<p>";
print $like . " " . $num;
print "<p>";
print "My favorite number is $num";
?>

This shows two examples of printing more than one thing. The first print line prints the
$like and $num variables, with the period [.* to separate them. The third print line prints
the $like variable, a blank space, and the $num variable, all separated with periods. The
fifth line also demonstrates how a variable can be used within the quotation marks [""*.

ë 
 !
      " ! 
   # they are CaSe SeNsitiVe,
they are always defined with a $, and they must start with a letter or an underscore (not
a number.) ëlso note that if needed you can dynamically build variables. For a more
thorough look at variables, see our Guide to Variables.

ë 
While a variable can hold a single piece of data, an array can hold a string of related
data. Its use may not be apparent right away, but will become clearer as we start using
loops and MySQL. Below is an example:
<?php
$friend[0* = "Justin";
$friend[1* = "Lloyd";
$friend[2* = "ëlexa";
$friend[3* = "Devron";

$age["Justin"* = 45;
$age["Lloyd"* = 32;
$age["ëlexa"* = 26;
$age["Devron"* = 15;

print "My friends names are " . $friend[0* . ", " . $friend[1* . ", " . $friend[2* . ", and " .
$friend[3*;

print "<p>";

print "ëlexa is " . $age["ëlexa"* . " years old";


?>

The first array ($friend) is arranged using integers as the key (the key is the information
between the [brackets*) which is handy when using loops. The second array ($age)
shows that you can also use a string (text) as the key. ës demonstrated the values are
called by print in the same way a regular variable would be.

      


      # they are CaSe SeNsitiVe, they are
always defined with a $, and they must start with a letter or an underscore (not a
number.)

  
You have probably all heard the term expression used in mathematics. We use
expressions in PHP to preform operations and give an answer to a single value. These
expressions are made up of two parts, the operators and the operands. The operands can
be variables, numbers, strings, boolean values, or other expressions. Here is an example:

=$+%

In this expression the operands are a, 3 and 4

 = &$'%( / )

In this expression the expression (3+4) is used as an operand along with b and 2.

 

Now that you understand what an operand is we can go into more detail about what
operators are. Operators tell us what to do with operands, and they fall into three major
categories:
O
 
 #
+(plus), - (minus), / (divided by), and * (multiplied by)

  #
> (greater than), < (less than), == (equal to), and != (not equal to)

c #
&& (true if both operands are true), || (true if at least one operand is true), xor (true if
ONLY one operand is true), and ! (true if a single operand is false)

Mathematical operators are exactly what they are called, they apply mathematical
functions to the operands. Comparison is also pretty straight forward, they compare one
operand to another operand. Boolean however may need a little more explaining.

Boolean is an extremely simple form of logic. In Boolean every statement is either True
or False. Think of a light switch, it must either be turned on or off, there is no in
between. Let me give you an example:

$a = true;
$b = true;
$c = false;

$a && $b;
This is asking for $a and $b to both be true, since they are both true, this expression is
TRU

$a || $b;
This is asking for $a or $b to be true. ëgain this is a TRU expression

$a xor $b;
This is asking for $a or $b, but not both, to be true. Since they are both true, this
expression is FëLS

! $a;
This is asking for $a to be false. Since $a is true, this expression is FëLS

! $c;
This is asking for $c to be false. Since that is the case, this expression is TRU

 
 



Conditionals allow your program to make choices. Following the same sort of boolean
logic you just learned about, the computer can only make two choices; true or false. In
the case of PHP this is accomplished using IF : LS statements. Below is an example
of an IF statement that would apply a senior's discount. If $over65 is false, everything
within the {brackets} is simply ignored.
<?php
$over65 = true;
$price = 1.00;
if ( $over65 )
{
$price = .90;
}
print "Your price is $" . $price;
?>

However, sometimes just the IF statement isn't enough, you need the LS statement as
well. When using just the IF statement the code within the brackets either will (true) or
will not (false) be executed before carrying on with the rest of the program. When we
add in the LS statement, if the statement is true it will execute the first set of code
and if it is false it will execute the second (LS) set of code. Here is an example:

<?php
$over65=true;
$price = 3.00;
if ($over65)
{
$discount =.90;
print "You have received our senior's discount, your price is $" . $price*$discount;
}
else
{
print "Sorry you do not qualify for a discount, your price is $" . $price;
}
?>

 
 
 
One useful thing to remember about conditional statements is that they can be nested
within each other. Below is an example of how the discount program from our example
could be written to use nested IF:LS statements. There are other ways of doing this -
such as using elseif () or switch () but this demonstrates how statements can be nested.
<?php
$age = 30;
$price = 3.00;
if ($age >65)
{
$discount =.90;
print "You have received our senior's discount, your price is $" . $price*$discount;
}
else
{
if ($age <18)
{
$discount =.95;
print "You have received our student's discount, your price is $" . $price*$discount;
}
else
{
print "Sorry you do not qualify for a discount, your price is $" . $price;
}
}
?>

This program will first check if they are eligible for the senior's discount. If they are not,
it will then check if they are eligible for a student discount, before returning the non-
discounted price.

[**
In PHP there are several different types of loops. Basically what a loop does is evaluate
a statement as true or false. If it is true it executes some code and then alters the original
statement and starts all over again by re-evaluating it. It continues to loop through the
code like this until the statement becomes false.

Here is an example in its simplest form:

<?php
$num = 1;
while ( $num <=10 )
{
print $num . " ";
$num++;
}
?>

Basically what this does is: while a number is greater than or equal to 10 it prints the
number. The '' adds one to the number, however this could also be phrased as + ,
+ '-. Once the number becomes greater than 10, in our case it becomes 11, then it
stops executing the code within the {brackets}

Below is an example of how you can combine a loop with a conditional

<?php
$num = 1;
while ( $num <=10 )
{
if ($num < 5)
{
print $num . " is less than 5 <br>";
}
else
{
print $num . " is not less than 5 <br>";
}
$num++;
}
?>
D*
ë FOR loop is very similar to a WHIL loop in that it continues to process a block of
code until a statement becomes false, however everything is defined in a single line. The
basic structure for a FOR loop is:

&

. 
 .  
(/ 
 
.0

Let's go back to our first example using the WHIL loop, where we printed out the
numbers 1 through 10 and do the same thing using a FOR loop.

<?php
for ($num=1; $num <= 10; $num++ )
{
print $num . " ";
}
?>

The FOR loop can also be used in conjunction with a conditional, just like we did with
the WHIL loop:

<?php
for ($num=1; $num <= 10; $num++ )
{
if ($num < 5)
{
print $num . " is less than 5 <br>";
}
else
{
print $num . " is not less than 5 <br>";
}
}
?>

Dë*
To understand FORëCH loops you have to remember what we learned about arrays.
If you recall an array (unlike a variable) contains a group of data. When using a loop
with an array, instead of having a counter that goes until proven false the FORëCH
loop continues until it has used all values in the array. So for example if an array
contained 5 pieces of data, then the FORëCH loop would execute 5 times. More uses
for arrays and FORëCH loops will become apparent when you start importing data
from MySQL.

ë FORëCH loop is phrased like this: Dë&     (/ 



.0

Here is an example of a FORëCH loop:


<?php
$a = array(1, 2, 3, 4, 5);
foreach ($a as $b)
{
print $b . " ";
}
?>

Once you understand that concept you can then use the FORëCH loop to do more
practical things. Let's say an array contains the ages of 5 family members. Then we will
make a FORëCH loop that will determine how much it costs for each of them to eat
on a buffet that has varied prices based on age. We will use the following pricing
system: Under 5 is free, 5-12 years costs $4 and over 12 years is $6.

<?php
$t = 0;
$age = array(33, 35, 13, 8, 4);
foreach ($age as $a)
{
if ($a < 5)
{$p = 0;}
else
{
if ($a <12)
{$p = 4;}
else
{$p = 6;}
}
$t = $t + $p;
print "$" . $p . "<br>";
}
print "The total is: $" . $t;
?>

D 
 
ë function is something that performs a specific task. People write functions if they
plan on doing the same task over and over again. This allows you to only write the code
once and save a lot of time and space.

ëlthough in the next few pages we will lean how to write our own functions, PHP has
several functions that already exist for us to use. ëlthough they all have different uses,
all functions are phrased as:  & !
(. The name being the name of the
function, and the argument being the value(s) it is using.

Here are some examples of functions already in PHP:

<?php
$a = abs(-.43);
$b = sqrt(16);
$c = round(12.3);
print "The absolute value of -.43 is " . $a . "<br>";
print "The square root of 16 is " . $b . "<br>";
print "12.3 rounded is " . $c . " and 12.5 rounded is " . round(12.5);
?>

This gives an example of three functions; absolute value, square root, and rounding. ës
you can see you can use the function right in the print statement or you can assign it to a
variable. ë list of functions can be found here.

  1

PHP has the ability to dynamically generate the time and date. Using a simple line of
code we are able to include this on our site, however it is important to know how the
formatting works.
<?php print time(); ?>

The above code outputs a long string of numbers. What these numbers represent is the
time based in the amount of seconds that have passed since January 1 1970 00:00:00
GMT. This number can also be assigned to a variable:

<?php
$b = time ();
print $b;
?>

ëlthough this is a handy feature, sometimes you want a more formatted and human
friendly representation of the date. You can use the date function in conjunction with
the time function to display this in the format of 
&
2
 (In our case we
want the start time to be now, so we will call the time first. We will demonstrate many
different types of formatting

<?php
$b = time ();
print date("m/d/y",$b) . "<br>";
print date("D, F jS",$b) . "<br>";
print date("l, F jS Y",$b) . "<br>";
print date("g:i ë",$b) . "<br>";
print date("r",$b) . "<br>";
print date("g:i:s ë D, F jS Y",$b) . "<br>";
?>

When you run this code you will see that the information is formatted in many different
ways. What each of the letters means for formatting is explained on the next page.

1
D 
 D

 !
ës you can see in our last example there are tons of different formats that can be used in
the date feature. Below is a summary of the variable used in date, and what each does.
   
 ë   
 #

1ë 
d - day of the month 2 digits (01-31)
j - day of the month (1-31)
D - 3 letter day (Mon - Sun)
l - full name of day (Monday - Sunday)
N - 1=Monday, 2=Tuesday, etc (1-7)
S - suffix for date (st, nd, rd)
w - 0=Sunday, 1=Monday (0-6)
z - day of the year (1=365)

[3
W - week of the year (1-52)

O
F - Full name of month (January - December)
m - 2 digit month number (01-12)
n - month number (1-12)
M - 3 letter month (Jan - Dec)
t - Days in the month (28-31)

ë
L - leap year (0 no, 1 yes)
o - ISO-8601 year number (x. 1979, 2006)
Y - four digit year (x. 1979, 2006)
y - two digit year (x. 79, 06)

O
a - am or pm
ë - ëM or PM
B - Swatch Internet time (000 - 999)
g - 12 hour (1-12)
G - 24 hour c (0-23)
h - 2 digit 12 hour (01-12)
H - 2 digit 24 hour (00-23)
i - 2 digit minutes (00-59)
s 0 2 digit seconds (00-59)

 e - timezone (x: GMT, CST)


I - daylight savings (1=yes, 0=no)
O - offset GMT (x: 0200)
Z - offset in seconds (-43200 - 43200)
r - full RFC 2822 formatted date

[
 !D 
 
While having pre-made functions is useful, for most things you are going to want the
flexibility to write your own custom functions. ë function you create takes this shape:
 
  
  &(/ 0

Below is an example of two simple functions:

<?php
function examplefunction ()
{
print "Hi, I'm a Function <br>";
}
function sqr( $num )
{
$NumSqr = $num * $num;
return $NumSqr;
}
Print "Sample Line 1 <br>";
examplefunction();
Print "Sample Line 3 <br>";
$a = 9;
$b = sqr( $a );
Print $a . "^2 = " . $b;
?>

ës you can see above, the code we defined between the { and } is all executed when we
call the function below. In our first example (examplefunction) we used the function to
simply print text. In our second function (sqr) we needed an operand to complete the
math within the function. We put this inside the parenthesis () after the function name.
We then add in the 4 line, so that the value is outputted to the spot in the code
where we originally called the function.

O D 
 [
 !
Functions can contain any of the information we have learned so far. Let's combine
functions with some of the material we learned earlier to create a multiplication table:
<?php
function mul()
{
global $start;
print "<tr>";
for ($num=1; $num <= 10; $num++ )
{
$cell = $num * $start;
print "<td> " . $cell . " </td>";
}
print "</tr>";
}
$start = 0;
print "<table border=1 cellpadding=3>";
while ( $start <=10 )
{
mul();
$start++;
}
print "</table>";
?>

One new thing you may have noticed is "´*cë*". Since the variable $start is not
defined within the function, we use the tag "GLOBëL" to let it know that it needs to use
the $start variable that we have defined outside of the function.

 

O5*
Interacting with MySQL makes PHP a far more powerful tool. In this tutorial we will
go through some of the most common ways PHP interacts with MySQL. To follow
along with what we are doing, you will need to create a database table by executing this
command:
CRëT TëBL friends (name VëRCHëR(30), fav_color VëRCHëR(30), fav_food
VëRCHëR(30), pet VëRCHëR(30));
INSRT INTO friends VëLUS ( "Rose", "Pink", "Tacos", "Cat" ), ( "Bradley",
"Blue", "Potatoes", "Frog" ), ( "Marie", "Black", "Popcorn", "Dog" ), ( "ënn",
"Orange", "Soup", "Cat" )

This will create a table for us to work with, that has friends' names, favorite colors,
favorite foods, and pets.

The first thing we need to do in our PHP file is connect to the database. We do that
using this code:

<?php
// Connects to your Database
mysql_connect("your.hostaddress.com", "username", "password") or
die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
?>

Of course you will replace server, username, password, and Database_Name with the
information relevant to your site. If you are unsure what these values are, contact your
hosting provider.


 1

Next we will retrieve the information from the database table we created called
"friends"
// Collects data from "friends" table
$data = mysql_query("SLCT * FROM friends")
or die(mysql_error());

ënd we will then temporally put this information into an array to use:
// puts the "friends" info into the $info array
$info = mysql_fetch_array( $data );

Now let's print out the data to see if it worked:

// Print out the contents of the entry


Print "<b>Name:</b> ".$info['name'* . " ";
Print "<b>Pet:</b> ".$info['pet'* . " <br>";

However this will only give us the first entry in our database. In order to retrieve all the
information, we need to make this a loop. Here is an example:

while($info = mysql_fetch_array( $data ))


{
Print "<b>Name:</b> ".$info['name'* . " ";
Print "<b>Pet:</b> ".$info['pet'* . " <br>";
}

So let's put all the these ideas together to create a nicely formatted table with this final
php code:

<?php
// Connects to your Database
mysql_connect("your.hostaddress.com", "username", "password") or
die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
$data = mysql_query("SLCT * FROM friends")
or die(mysql_error());
Print "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data ))
{
Print "<tr>";
Print "<th>Name:</th> <td>".$info['name'* . "</td> ";
Print "<th>Pet:</th> <td>".$info['pet'* . " </td></tr>";
}
Print "</table>";
?>

5*5   

Now that you have done one query, you can do more complicated queries using the
same basic syntax. If you have forgotten the queries, you can review them in the
MySQL glossary.

Let's try to do a query of our database for people who have cats for a pet. We will do
this by adding a WHR clause to set pet equal to Cat.

<?php
// Connects to your Database
mysql_connect("your.hostaddress.com", "username", "password") or
die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
$data = mysql_query("SLCT * FROM friends WHR pet='Cat'")
or die(mysql_error());
Print "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data ))
{
Print "<tr>";
Print "<th>Name:</th> <td>".$info['name'* . "</td> ";
Print "<th>Color:</th> <td>".$info['fav_color'* . "</td> ";
Print "<th>Food:</th> <td>".$info['fav_food'* . "</td> ";
Print "<th>Pet:</th> <td>".$info['pet'* . " </td></tr>";
}
Print "</table>";
?>


  
Following this same structure, we can connect to a database and create new tables. ët
the end we will print a line, so we know that it is done executing:
<?php
// Connects to your Database
mysql_connect("your.hostaddress.com", "username", "password") or
die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
mysql_query("CRëT TëBL tablename ( name VëRCHëR(30),
age INT, car VëRCHëR(30))");

Print "Your table has been created";


?>

I find this method is often used when installing a PHP program someone else has
written. Often an install file includes a way for the user to update the MySQL database
from the browser. This allows people less familiar with the code to install the program
more easily.

  

  
We can use the same method of using SQL commands to populate our database as we
did to create it. Here is an example:
<?php
// Connects to your Database
mysql_connect("your.hostaddress.com", "username", "password") or
die(mysql_error()); mysql_select_db("Database_Name") or die(mysql_error());
mysql_query("INSRT INTO tablename VëLUS ( 'Bill', 29, 'Ford' ), ( 'Mike', 16,
'Beetle' ), ( 'ëlisa', 36, 'Van' )");

Print "Your table has been populated";


?>

 ! D
Sometimes it is useful to collect data from your website users and store this information
in a MySQL database. We have already seen you can populate a database using PHP,
now we will add the practicality of allowing the data to be added through a user friendly
web form.

The first thing we will do is create a page with a form. For our demonstration we will
make a very simple one:

<form action="process.php" method="post">


Your Name: <input type="text" name="name"><br>
-mail: <input type="text" name = "email"><br>
Location: <input type="text" name = "location"><br>
<input type="submit" value="Submit">
</form>

  

6ë !1
 D
Next you need to make process.php, the page that our form sends its data to. Here is an
example of how to collect this data to post to the MySQL database:
<?
$name=$_POST['name'*;
$email=$_POST['email'*;
$location=$_POST['location'*;
mysql_connect("your.hostaddress.com", "username", "password") or
die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
mysql_query("INSRT INTO `data` VëLUS ('$name', '$email', '$location')");
Print "Your information has been successfully added to the database.";
?>

ës you can see the first thing we do is assign variables to the data from the previous
page. We then just query the database to add this new information.

Of course before we try it we need to make sure the table actually exists. xecuting this
code should create a table that can be used with our sample files:

CRëT TëBL data (name VëRCHëR(30), email VëRCHëR(30), location


VëRCHëR(30));

ëD 4 


Now you know how to store user data in MySQL, so let's take it one step farther and
learn how to upload a file for storage. First let's make our sample database:
CRëT TëBL uploads (id INT(4) NOT NULL ëUTO_INCRMNT PRIMëRY
KY, description CHëR(50), data LONGBLOB, filename CHëR(50), filesize
CHëR(50), filetype CHëR(50) );
The first thing you should notice is a field called 
that is set to
ë47O. What this data type means is that it will count up to assign
each file a unique file ID starting at 1 and going to 9999 (since we specified 4 digits).
You will also probably notice that our data field is called *´c*c There are
many types of BLOB as we have mentioned before. TINYBLOB, BLOB,
MDIUMBLOB, and LONGBLOB are your options, but we set ours to LONGBLOB
to allow for the largest possible files.

Next, we will create a form to allow the user to upload her file. This is just a simple
form, obviously you could dress it up if you wanted:

<form method="post" action="upload.php" enctype="multipart/form-data">


Description:<br>
<input type="text" name="form_description" size="40">
<input type="hidden" name="Më _FIL_SIZ" value="1000000">
<br>File to upload:<br>
<input type="file" name="form_data" size="40">
<p><input type="submit" name="submit" value="submit">
</form>

c  

"  
 
  
 2
 

8

ë !D 4 


O5*
Next we need to actually create upload.php, which will take our users file and store it in
our database. Below is sample coding for upload.php.
<?php
mysql_connect("your.server.com","username","password");
mysql_select_db("database_name");
$data = addslashes(fread(fopen($form_data, "r"), filesize($form_data)));
$result=MYSQL_QURY("INSRT INTO uploads (description,
data,filename,filesize,filetype) ". "VëLUS
('$form_description','$data','$form_data_name','$form_data_size','$form_data_type')");
$id= mysql_insert_id();
print "<p>File ID: <b>$id</b><br>";
print "<p>File Name: <b>$form_data_name</b><br>";
print "<p>File Size: <b>$form_data_size</b><br>";
print "<p>File Type: <b>$form_data_type</b><p>";
print "To upload another file <a href=http://www.yoursite.com/yourpage.html> Click
Here</a>";
?>

Learn more about what this actually does on the next page.

ë !4    


The first thing this code actually does is connect to the database (you need to replace
this with your actual database information.)
Next it uses the ë11*ë function. What this does is add back slashes if needed
into the file name so that we won't get an error when we query the database. For
example if we have Billy'sFile.gif, it will convert this to Billy\'sFile.gif. D opens
the file and Dë1 is a binary safe file read, so that the ë11*ë is applied to
data within the file if needed.

Next we add all of the information our form collected into our database. You will notice
we listed the fields first, and the values second so we don't accidently try to insert data
into our first field (the auto assigning ID field.)

Finally we print out the data for the user to review.


  !D 
We already learned how to retrieve plain data from our MySQL database. Likewise,
storing your files in a MySQL database wouldn't be very practical if there wasn't a way
to retrieve them. The way we are going to learn to do this is by assigning each file a
URL based on their ID number. If you will recall when we uploaded the files we
automatically assigned each of the files an ID number. We will use that here when we
call the files back. Save this code as download.php
<?php
mysql_connect("your.server.com","username","password");
mysql_select_db("database_name");
$query = "SLCT data,filetype FROM uploads where id=$id";
$result = MYSQL_QURY($query);
$data = MYSQL_RSULT($result,0,"data");
$type = MYSQL_RSULT($result,0,"filetype");
Header( "Content-type: $type");
print $data;
?>

Now to retrieve our file, we point our browser to:


http://www.yoursite.com/download.php?id=2 (replace the 2 with whatever file ID you
want to download/display)

This code is the base for doing a lot of things. With this as a base you can add in a
database query that would list files, and put them in a drop down menu for people to
choose. Or you could set ID to be a randomly created number so that a different graphic
from your database is randomly displayed each time a person visits. The possibilities
are endless.

   !D 
Here is a  way of removing files from the database. You want to    
with this one!! Save this code as remove.php
<?php
mysql_connect("your.server.com","username","password");
mysql_select_db("database_name");
$query = "DLT FROM uploads where id=$id";
$delete = MYSQL_QURY($query);
print "File ID $id has been removed from the database";
?>

Like our previous code that downloaded files, this script allows files to be removed just
by typing in their URL: http://yoursite.com/remove.php?id=2 (replace 2 with the ID you
want to remove.) For obvious reasons, you want to     

 . This is of
course for demonstration, when we actually build applications we will want to put in
safeguards that ask the user if they are sure they want to delete, or perhaps only allow
people with a password to remove files. This simple code is the base we will build on to
do all of those things.


 1
  
On our site, we have tutorials about adding data to a MySQL database, and tutorials
about uploading files, but recently one of our forum users asked:
"I know how to submit data into a mySQL table through a form. Now I want to upload
the image file to the remote directory (say, 'images/') but at the same time save the file-
name in the table. "
This is a very common question because it has a lot of uses. Often you want a user to be
able to upload a photo, but you don't want to bog down your database space by saving
all the images directly into the database. You instead save the image to your server, but
keep a record in the database of what file was saved so you can easily reference the
image when needed. First let's create a database:
CRëT TëBL employees (name VëRCHëR(30), email VëRCHëR(30), phone
VëRCHëR(30), photo VëRCHëR(30))
This SQL code creates a database called 'employees' that can hold their name, email,
phone and the name of their photo.
|


 ! D
<form enctype="multipart/form-data" action="add.php" method="POST">
Name: <input type="text" name="name"><br>
-mail: <input type="text" name = "email"><br>
Phone: <input type="text" name = "phone"><br>
Photo: <input type="file" name="photo"><br>
<input type="submit" value="ëdd">
</form>
This is simply an HTML form that you would use to collect information to be added to
the database. We could add more fields if we wanted, but then we would also need to
add the appropriate fields to our MySQL database.
|

  !
 1

<?php
//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILS['photo'*['name'*);

//This gets all the other information from the form


$name=$_POST['name'*;
$email=$_POST['email'*;
$phone=$_POST['phone'*;
$pic=($_FILS['photo'*['name'*);

// Connects to your Database


mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error())
;
mysql_select_db("Database_Name") or die(mysql_error()) ;

//Writes the information to the database


mysql_query("INSRT INTO `employees` VëLUS ('$name', '$email', '$phone',
'$pic')") ;

//Writes the photo to the server


if(move_uploaded_file($_FILS['photo'*['tmp_name'*, $target))
{

//Tells you if its all ok


echo "The file ". basename( $_FILS['uploadedfile'*['name'*). " has been uploaded, and
your information has been added to the directory";
}
else {

//Gives and error if its not


echo "Sorry, there was a problem uploading your file.";
}
?>
This code should be saved as add.php. To understand what each step of this script is
doing it is best to read the comments within the code. Basically it gathers the
information from the form and then writes it to the MySQL database. Once that is done,
it saves the file to the /images directory (relative to the script) on your server.

If you are only allowing photo uploads, you might consider limiting the allowed file
types to jpg, gif and png. We also don't check if the file already exists, so if two people
both upload a file called MyPic.gif, one will overwrite the other. ë simple way to
remedy this would be to simply rename each file with a unique ID.

  ! 1

<?php
// Connects to your Database
mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error())
;
mysql_select_db("Database_Name") or die(mysql_error()) ;

//Retrieves data from MySQL


$data = mysql_query("SLCT * FROM employees") or die(mysql_error());

//Puts it into an array


while($info = mysql_fetch_array( $data ))
{

//Outputs the image and other data


cho "<img src=http://www.yoursite.com/images/".$info['photo'* ."> <br>";
cho "<b>Name:</b> ".$info['name'* . "<br> ";
cho "<b>mail:</b> ".$info['email'* . " <br>";
cho "<b>Phone:</b> ".$info['phone'* . " <hr>";
}
?>

This script very simply queries the database and retrieves all of the information in it. It
then echos each back until it has shown all the data.

To show the image, we just use normal HTML for the image, and only change the last
part (the actual image name) with the image name stored in our database. For more
information on retrieving information from the database, read this tutorial.

 O*D
This script will allow you to upload files from your browser to your hosting, using PHP.
The first thing we need to do is create an HTML form that allows people to choose the
file they want to upload.
<form enctype="multipart/form-data" action="upload.php" method="POST">
Please choose a file: <input name="uploaded" type="file" /><br />
<input type="submit" value="Upload" />
</form>
This form sends data to the file "upload.php", which is what we will be creating next to
actually upload the file.

4  !
 D 
The actual file upload is very simple:
<?php
$target = "upload/";
$target = $target . basename( $_FILS['uploaded'*['name'*) ;
$ok=1;
if(move_uploaded_file($_FILS['uploaded'*['tmp_name'*, $target))
{
echo "The file ". basename( $_FILS['uploadedfile'*['name'*). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>
This very small piece of code will upload files sent to it by your HTML form.

1.| The first line †   


 is where we assign the folder that files will be
uploaded to. ës you can see in the second line, this folder is relative to the
upload.php file. So for example, if your file was at
www.yours.com/files/upload.php then it would upload files to
www.yours.com/files/upload/yourfile.gif. Be sure you remember to create this
folder!
2.| We are not using † at the moment but we will later in the tutorial.
3.| We then move the uploaded file to where it belongs using R


. This places it in the directory we specified at the beginning of our script. If
this fails the user is given an error message, otherwise they are told that the file
has been uploaded.
%|*

 D 9 
5.| if ($uploaded_size > 350000)
{
echo "Your file is too large.<br>";
$ok=0;
}
6.| ëssuming that you didn't change the form field in our HTML form (so it is still
named uploaded), this will check to see the size of the file. If the file is larger
than 350k, they are given a file too large error, and we set $ok to equal 0.
7.| You can change this line to be a larger or smaller size if you wish by changing
350000 to a different number. Or if you don't care about file size, just leave
these lines out.
|*
D  
9.| if ($uploaded_type =="text/php")
{
echo "No PHP files<br>";
$ok=0;
}
10.|The code above checks to be sure the user is not uploading a PHP file to your
site. If they do upload a PHP file, they are given an error, and $ok is set to 0.
11.|if (!($uploaded_type=="image/gif")) {
echo "You may only upload GIF files.<br>";
$ok=0;
}
12.|In our second example we only allow users to upload .gif files, and all other
types are given an error before setting $ok to 0. You can use these basic
examples to allow or deny any specific file types.
-$| 

 !
!
 
14.|<?php
$target = "upload/";
$target = $target . basename( $_FILS['uploaded'*['name'*) ;
$ok=1;

//This is our size condition


if ($uploaded_size > 350000)
{
echo "Your file is too large.<br>";
$ok=0;
}

//This is our limit file type condition


if ($uploaded_type =="text/php")
{
echo "No PHP files<br>";
$ok=0;
}

//Here we check that $ok was not set to 0 by an error


if ($ok==0)
{
cho "Sorry your file was not uploaded";
}

//If everything is ok we try to upload it


else
{
if(move_uploaded_file($_FILS['uploaded'*['tmp_name'*, $target))
{
echo "The file ". basename( $_FILS['uploadedfile'*['name'*). " has been
uploaded";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
}
?>

-:| D !

16.|Obviously if you are allowing file uploads you are leaving yourself open to
people uploading lots of undesirable things. One precaution is not allowing them
to upload any php, html, cgi, etc. files that could contain malicious code. This
provides more safety but is not sure fire protection.
17.|ënother idea is to make the upload folder private, so that only you can see it.
Then once you have seen what has been uploaded, you can approve (move) it or
remove it. Depending on how many files you plan on receiving t his could be
time consuming and impractical.
18.|In short, this script is probably best kept in a private folder. We don't
recommend putting it somewhere where the public can use it, or you may end up
with a server full of useless or potentially dangerous files. If you really want the
general public to be able to utilize your server space, we suggest writing in as
much security as possible.