Sunteți pe pagina 1din 104

PHP Variables

A variable is used to store information.

Variables in PHP
Variables are used for storing values, like text strings, numbers or arrays.
When a variable is declared, it can be used over and over again in your script.
All variables in PHP start with a $ sign symbol.
The correct way of declaring a variable in PHP:
$var_name = value;
New PHP programmers often forget the $ sign at the beginning of the variable. In that case it will
not work.
Let's try creating a variable containing a string, and a variable containing a number:
<?php
$txt="Hello World!";
$x=16;
?>

PHP is a Loosely Typed Language


In PHP, a variable does not need to be declared before adding a value to it.
In the example above, you see that you do not have to tell PHP which data type the variable is.
PHP automatically converts the variable to the correct data type, depending on its value.
In a strongly typed programming language, you have to declare (define) the type and name of
the variable before using it.
In PHP, the variable is declared automatically when you use it.

Naming Rules for Variables

A variable name must start with a letter or an underscore "_"


A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9,
and _ )

A variable name should not contain spaces. If a variable name is more than one word, it
should be separated with an underscore ($my_string), or with capitalization ($myString )

PHP variables - Types of variables in PHP


PHP variables can have different types; among those, we can distinguish:

booleans, that is to say one of the two values TRUE or FALSE


integers, which are elements of the set Z = {...,-2,-1,0,1,2,...}
floating point numbers (also called "doubles" or "real numbers"), which represent numbers
with decimals.
strings, which are series of characters put between quotes; for instance, 'a black cat' is a string.
arrays, which are tables indexed by keys (we will give an introduction to arrays in another PHP
tutorial)
objects, which are user-defined.
resources, which refer to external resources. Resource variables are created by special PHP
functions.
the NULL value, which denotes the fact that a variable has no value. A variable has NULL value if
it has been assigned the NULL value, if it hasn't yet been set, or if it has been unset. You can test
whether a PHP variable has NULL value by using the function is_null() (which will return TRUE if
the tested PHP variable is NULL and FALSE otherwise).
pseudo-types, which are hybrid PHP types. For instance, mixed indicates that a parameter can
be of various types (the function gettype() takes mixed parameters); another example is the
pseudo-type number, which denotes an integer or a floating point number.

Absence of type definition in PHP


When declaring a variable in PHP, you do not need to define its type; indeed, PHP is very weakly
typed and the type of a variable will be automatically determined by the type of content that was
assigned to it. You can have a look at the example below for a demonstration of this fact:
Learn the PHP code:
<html>
<body>
<?php
$var = 2;
echo $var.'
'.gettype($var).'<br>';
$var='mycomputerforum';
echo $var.' '.gettype($var);
?>
</body>
</html>

Remark:

the point . is the concatenation operator (it allows you to "stick together" different strings; since
PHP is a very weakly typed language, the $var variable in the example above is interpreted as a
string when the concatenation operator is used).
Functions related to the types of variables in PHP
Several functions allow you to manipulate the type of a variable in PHP; we enumerate below a
few of them (the list is in no way exhaustive):
isset() returns TRUE if the PHP variable it receives has been set and FALSE otherwise.
unset() allows you to "empty" a variable (i.e. to reinitialize it, or in other words to "free" it; in
particular, the variable which is unset will lose its type and will be assigned the NULL value).
gettype() returns the type of the PHP variable it receives (cf. example above).
is_string() returns TRUE if the variable received is a string, FALSE otherwise. By the same token,
you can use the functions is_integer(), is_float(), is_array(), etc ...
PHP variables - Assignment of variables in PHP
There are two ways to assign a variable in PHP.

Assignment by value
With the assignment by value (which is the most often used way to define a variable), a variable
is assigned a value only. For instance, setting $var2 = $var1 will assign the value of $var1 to
the new variable $var2; if later on in the script the variable $var1 is changed, the variable $var2
will remain unchanged ($var2 will keep the value at which it was first defined). The example
below is illustrating the assignment of PHP variables by value.
Learn the HTML code:
<html>
<body>
<?php
$var1 = 1;
$var2 =
$var1;
echo $var2.'
';
$var1 = 0;
echo $var2;
?>
</body>
</html>

Run the PHP script in your web browser:

Assignment by reference

After you assign a variable by reference, the variable points to a location in memory instead of
merely storing a given value as in an assignment by value. A sa result, the value of this variable
will be modified whenever the value stored at this memory address is changed.
When you are assigning a variable $var1 by reference to another variable $var2, the only
difference in the PHP syntax is that you must add an ampersand & before $var1:
Learn the PHP code:
<html>
<body>
<?php
$var1 = 1;
$var2 =
~$var1;
echo
$var2.'<br>';
$var1 = 0;
echo $var2;
?>
</body>
</html>

PHP variables - Variable scope in PHP


PHP variables can have various scopes (the scope of a variable determines the perimeter within
which the variable can be used).
Most variables have a global scope (that of the current file, plus all the files which are included
or required -more about this later-).
However, it can happen that a variable is used only locally (local variables): this is for instance
the case for variables which are used within a function (you can learn about the definition of
functions in another PHP tutorial). Have a look at the example below:
Learn the PHP code:
<html>
<body>
<?php
$var1 = 1;
function
print_between_stars()
{
echo '*'.$var1.'*';
}

print_between_stars();
?>
</body>
</html>

Explanation:
In the example above, $var1 is considered as a local variable within the function
print_between_stars(). Therefore, its previous definition won't be taken into account, so that
calling the function print_between_stars() will return nothing but two stars (along with a warning
stating that $var1 hasn't been set).
If you want to be able to use the first instantiation of $var1 within the function, you must first
declare it as global within the function:
Learn the PHP code:
<html>
$var1 = 1;
function
print_between_stars()
{
global $var1;
echo '*'.$var1.'*';
}
print_between_stars();
<body>
<?php
?>
</body>
</html>

Run the PHP script in the web browser:


Remark:
Since the PHP variable $var1 has been declared global, its initial value has been passed on
successfully at the function level.

Static variables
A static variable is local within a function but keeps its value after the function has been
executed (unlike purely local functions which are reinitialized upon execution of the function, i.e.
after a change in scope)).

Learn the PHP code:


<html>
<body>
<?php
function
print_between_stars()
{
static $var = 0;
$var = $var + 1;
echo $var; }
print_between_stars();
print_between_stars();
?>
</body>
</html>

PHP Constants
A constant is a name to which is assigned a constant value (constant because it won't be able to
be changed during the script execution; additionally, a constant automatically has a global
scope). It is defined according to the syntax define("CONSTANT_NAME",VALUE), where
CONSTANT_NAME is the name of your constant and VALUE its value.
Learn the PHP code:
<html>
<body>
<?php
define("MY_CONSTANT",
2);
echo MY_CONSTANT;
?>
</body>
</html>

Reserved predefined variables


PHP allows you to access various reserved predefined variables; for instance, $GLOBAL is an
array which contains all the global variables used within the script, the keys of this array being
the names of these global variables.
The $GLOBAL variable, like the other reserved predefined variables (some of which will be

introduced later in the next PHP tutorials), is automatically a global variable, meaning that it can
be accessed from anywhere in the script. For this reason, it is called a superglobal variable.
For instance, one of our examples above could be rewritten:
Learn the PHP code:
<html>
<body>
<?php
$var1 = 1;
function
print_between_stars()
{
echo '*'.
$GLOBALS['var1'].'*';
}
print_between_stars();
?>
</body>
</html>

The result returned is the same as if the variable $var1 had been declared global by using the
keyword global within the function.

PHP variables - Variable variables in PHP


A variable variable allows you to dynamically create new PHP variables as the PHP script is being
executed; it has the form $$var, where $var denotes a usual PHP variable whose value will
become the name of a new variable. The PHP script below illustrates how you can generate new
variables thanks to variable variables:
Learn the PHP code:
<html>
<body>
<?php
$var = 'new';
$$var = 'new variable
definition';
echo $new;
?>
</body>

</html>

Remarks:
A new PHP variable called $new has been created by the variable variable $$var.
In the same way, it is possible to define variable variable variables (of the form $$$var), etc ...
this is done iteratively starting from the definition of a variable variable.

A PHP variable can have different types but no definition of type is needed since it is
automatically determined when the variable is assigned a value: PHP is indeed a very weakly
typed programming language, which offers you great flexibility but also requires great attention
(because it is easier to make mistakes when types are not defined beforehand by the
programmer).
A PHP variable can be assigned by value (in which case the PHP variable simply stores a value)
or by reference (in which case the PHP variable stores a pointer to a location in memory;
therefore, the value of the variable will change whenever the value located at this memory
address is changed).
A PHP variable can have different scopes (local, global) and there exist some reserved predefined
variables which can be used anywhere in the script: because such variables are automatically
global, they are called superglobals (or superglobal variables).
Variable variables can be used to dynamically generate new PHP variables as the execution of
your PHP script unfolds: it can prove to be practical whenever you do not know beforehand the
names of the variables that will have to be generated.

Arrays
An array stores multiple values in one single variable.

What is an Array?
A variable is a storage area holding a number or text. The problem is, a variable will hold only
one value.
An array is a special variable, which can store multiple values in one single variable.
If you have a list of items (a list of car names, for example), storing the cars in single variables
could look like this:
However, what if you want to loop through the cars and find a specific one? And what if you had
not 3 cars, but 300?
The best solution
$cars1="Saab";
$cars2="Volvo";
$cars3="BMW";
here is to use an array!
An array can hold all your variable values under a single name. And you can access the values by
referring to the array name.

Each element in the array has its own index so that it can be easily accessed.
In PHP, there are three kind of arrays:
Numeric array - An array with a numeric index
Associative array - An array where each ID key is associated with a value
Multidimensional array - An array containing one or more array

Numeric Arrays
A numeric array stores each array element with a numeric index.
There are two methods to create a numeric array.
1. In the following example the index are automatically assigned (the index starts at 0):
$cars=array("Saab","Volvo","BMW","Toyota");
2. In the following example we assign the index manually:
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
Example
In the following example you access the variable values by referring to the array name and
index:
<?php
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
echo $cars[0] . " and " . $cars[1] . " are Swedish cars.";
?>
The code above will output:
Saab and Volvo are Swedish cars.

Associative Arrays
An associative array, each ID key is associated with a value.
When storing data about specific named values, a numerical array is not always the best way to
do it.
With associative arrays we can use the values as keys and assign values to them.
Example 1
In this example we use an array to assign ages to the different persons:
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
Example 2
This example is the same as example 1, but shows a different way of creating the array:

$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
The ID keys can be used in a script:
<?php
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
echo "Peter is " . $ages['Peter'] . " years old.";
?>

Peter is 32 years old.


The code above will output:

Multidimensional Arrays
In a multidimensional array, each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on.
Example
In this example we create a multidimensional array, with automatically assigned ID keys:
$families = array
(
"Griffin"=>array
(
"Peter",
"Lois",
"Megan"
),
"Quagmire"=>array
(
"Glenn"
),
"Brown"=>array
(
"Cleveland",
"Loretta",
"Junior"
) );
The array above would look like this if written to the output:
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois

[2] => Megan


)
[Quagmire] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
))
Example 2
Lets try displaying a single value from the array above:
echo "Is " . $families['Griffin'][2] .
" a part of the Griffin family?";

output
Is Megan a part of the Griffin family?

PHP Forms and User Input


The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input.

PHP Form Handling


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 your PHP scripts.
Example
The example below contains an HTML form with two input fields and a submit button:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
When a user fills out the form above and click on the submit button, the form data is sent to a
PHP file, called "welcome.php":
"welcome.php" looks like this:
<html>
<body>
Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old.

</body>
</html>
Output could be something like this:
Welcome John!
You are 28 years old.
The PHP $_GET and $_POST functions will be explained in the next chapters.

Form Validation
User input should be validated on the browser whenever possible (by client scripts). Browser
validation is faster and reduces the server load.
You should consider server validation if the user input will be inserted into a database. A good
way to validate a form on the server is to post the form to itself, instead of jumping to a different
page. The user will then get the error messages on the same page as the form. This makes it
easier to discover the error.

PHP Switch Statement


Conditional statements are used to perform different actions based on different conditions.

The PHP Switch Statement


Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
This is how it works: First we have a single expression n (most often a variable), that is evaluated
once. The value of the expression is then c=ompared with the values for each case in the
structure. If there is a match, the block of code associated with that case is executed. Use break
to prevent the code from running into the next case automatically.
The default statement is used if no match is found.
Example
<html>
<body>
<?php
switch ($x)
{
case 1:

echo "Number 1";


break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}
?>
</body>
</html>

PHP String Variables


A string variable is used to store and manipulate text.

String Variables in PHP


String variables are used for values that contain characters.
In this chapter we are going to look at the most common functions and operators used to
manipulate strings in PHP.
After we create a string we can manipulate it. A string can be used directly in a function or it can
be stored in a variable.
Below, the PHP script assigns the text "Hello World" to a string variable called $txt:
<?php
$txt="Hello World";
echo $txt;
?>

output-

Hello World

Now, lets try to use some different functions and operators to manipulate the string.

The Concatenation Operator


There is only one string operator in PHP.
The concatenation operator (.) is used to put two string values together.
To concatenate two string variables together, use the concatenation operator:
<?php
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;
?>

output- Hello World! What a nice day!

If we look at the code above you see that we used the concatenation operator two times. This is
because we had to insert a third string (a space character), to separate the two strings.

The strlen() function


The strlen() function is used to return the length of a string.

Let's find the length of a string:


<?php
echo strlen("Hello world!");
?>

output-12

The length of a string is often used in loops or other functions, when it is important to know when
the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the
string).

The strpos() function


The strpos() function is used to search for a character/text within a string.
If a match is found, this function will return the character position of the first match. If no match
is found, it will return FALSE.
Let's see if we can find the string "world" in our string:
<?php
echo strpos("Hello world!","world");
?>

output-6

The position of the string "world" in the example above is 6. The reason that it is 6 (and not 7), is
that the first character position in the string is 0, and not 1.

PHP MySQL Connect to a Database


The free MySQL database is very often used with PHP.

Create a Connection to a MySQL Database


Before you can access data in a database, you must create a connection to the database.
In PHP, this is done with the mysql_connect() function.
Syntax
mysql_connect(servername,username,password);
Parameter

Description

servername

Optional. Specifies the server to connect to. Default value is "localhost:3306"

username

Optional. Specifies the username to log in with. Default value is the name of
the user that owns the server process

password

Optional. Specifies the password to log in with. Default is ""

Note: There are more available parameters, but the ones listed above are the most important.
Example
In the following example we store the connection in a variable ($con) for later use in the script.
The "die" part will be executed if the connection fails:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());

}
// some code
?>
Closing a Connection
The connection will be closed automatically when the script ends. To close the connection before,
use the mysql_close() function:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_close($con);
?>

PHP Database ODBC


ODBC is an Application Programming Interface (API) that allows you to connect to a data source
(e.g. an MS Access database).

Create an ODBC Connection


With an ODBC connection, you can connect to any database, on any computer in your network,
as long as an ODBC connection is available.
Here is how to create an ODBC connection to a MS Access Database:
1.
2.
3.
4.
5.
6.
7.
8.

Open the Administrative Tools icon in your Control Panel.


Double-click on the Data Sources (ODBC) icon inside.
Choose the System DSN tab.
Click on Add in the System DSN tab.
Select the Microsoft Access Driver. Click Finish.
In the next screen, click Select to locate the database.
Give the database a Data Source Name (DSN).
Click OK.

Note that this configuration has to be done on the computer where your web site is located. If
you are running Internet Information Server (IIS) on your own computer, the instructions above
will work, but if your web site is located on a remote server, you have to have physical access to
that server, or ask your web host to to set up a DSN for you to use.

Connecting to an ODBC
The odbc_connect() function is used to connect to an ODBC data source. The function takes four
parameters: the data source name, username, password, and an optional cursor type.
The odbc_exec() function is used to execute an SQL statement.
Example
The following example creates a connection to a DSN called northwind, with no username and no
password. It then creates an SQL and executes it:

$conn=odbc_connect('northwind','','');
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);

Retrieving Records
The odbc_fetch_row() function is used to return records from the result-set. This function returns
true if it is able to return rows, otherwise false.
The function takes two parameters: the ODBC result identifier and an optional row number:
odbc_fetch_row($rs)

Retrieving Fields from a Record


The odbc_result() function is used to read fields from a record. This function takes two
parameters: the ODBC result identifier and a field number or name.
The code line below returns the value of the first field from the record:
$compname=odbc_result($rs,1);
The code line below returns the value of a field called "CompanyName":
$compname=odbc_result($rs,"CompanyName");

Closing an ODBC Connection


The odbc_close() function is used to close an ODBC connection.
odbc_close($conn);

An ODBC Example
The following example shows how to first create a database connection, then a result-set, and
then display the data in an HTML table.
<html>
<body>
<?php
$conn=odbc_connect('northwind','','');
if (!$conn)
{exit("Connection Failed: " . $conn);}
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
if (!$rs)
{exit("Error in SQL");}
echo "<table><tr>";
echo "<th>Companyname</th>";
echo "<th>Contactname</th></tr>";
while (odbc_fetch_row($rs))
{
$compname=odbc_result($rs,"CompanyName");
$conname=odbc_result($rs,"ContactName");
echo "<tr><td>$compname</td>";
echo "<td>$conname</td></tr>";
}
odbc_close($conn);
echo "</table>";

?>
</body>

PHP MySQL Create Database and Tables


A database holds one or multiple tables.

Create a Database
The CREATE DATABASE statement is used to create a database in MySQL.
Syntax
CREATE DATABASE database_name
To learn more about SQL, please visit our.
To get PHP to execute the statement above we must use the mysql_query() function. This
function is used to send a query or command to a MySQL connection.
Example
The following example creates a database called "my_db":
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
mysql_close($con);
?>

Create a Table
The CREATE TABLE statement is used to create a table in MySQL.
Syntax
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)
To learn more about SQL, please visit our.

We must add the CREATE TABLE statement to the mysql_query() function to execute the
command.
Example
The following example creates a table named "Persons", with three columns. The column names
will be "FirstName", "LastName" and "Age":
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
// Create table
mysql_select_db("my_db", $con);
$sql = "CREATE TABLE Persons
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
// Execute query
mysql_query($sql,$con);
mysql_close($con);
?>
Important: A database must be selected before a table can be created. The database is
selected with the mysql_select_db() function.
Note: When you create a database field of type varchar, you must specify the maximum length
of the field, e.g. varchar(15).
The data type specifies what type of data the column can hold. For a complete reference of all
the data types available in MySQL, go to our complete.

Primary Keys and Auto Increment Fields


Each table should have a primary key field.
A primary key is used to uniquely identify the rows in a table. Each primary key value must be
unique within the table. Furthermore, the primary key field cannot be null because the database
engine requires a value to locate the record.
The following example sets the personID field as the primary key field. The primary key field is
often an ID number, and is often used with the AUTO_INCREMENT setting. AUTO_INCREMENT
automatically increases the value of the field by 1 each time a new record is added. To ensure
that the primary key field cannot be null, we must add the NOT NULL setting to the field.

Example
$sql = "CREATE TABLE Persons
(
personID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(personID),
FirstName varchar(15),
LastName varchar(15),
Age int
)";
mysql_query($sql,$con);

The + Operator Used on Strings


The + operator can also be used to add string variables or text values together.
To add two or more string variables together, use the + operator.
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
After the execution of the statements above, the variable txt3 contains "What a verynice day".
To add a space between the two strings, insert a space into one of the strings:
txt1="What a very ";
txt2="nice day";
txt3=txt1+txt2;
or insert a space into the expression:
txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;
After the execution of the statements above, the variable txt3 contains:
"What a very nice day"

(Adding Strings and Numbers)The rule is: If you add a number and
a string, the result will be a string!
Example
x=5+5;
document.write(x);
x="5"+"5";
document.write(x);
x=5+"5";
document.write(x);
x="5"+5;
document.write(x);

MySQL - Triggers

What are triggers? What are they used for?


A trigger is a set of code which is executed in response to some event.
E.g Update employee_perfomance table when a new task is inserted in task table. Here, the
trigger is update and the event is inserting a new row.
A trigger in MySQL is created using CREATE TRIGGER trigger_name. We need to specify the
trigger type.
Triggers can be used for actively control, monitor, and manage a group of tables whenever an
insert, update, or delete operation is performed.

Write syntax for Creating triggers and Dropping Triggers along with example
for each of them.
Create trigger
Syntax:
Create trigger trigger_name
ON table_name
{
FOR [delete][update][insert]
AS
Sql statements
}
Example:
CREATE TRIGGER reminder
ON titles
FOR INSERT, UPDATE
AS some_function (50009, 16, 10)

Drop a trigger
Syntax
DROP TRIGGER Trigger_name
Example:
Drop trigger reminder

What are the types of triggers? Explain each of them. Insert


triggers, Delete triggers and Update triggers.
Types of triggers:
Insert trigger: this trigger is invoked after or before an insert on some table.
Example:
CREATE TRIGGER new_employee
After INSERT ON employee
FOR EACH ROW

Sql statement
Update trigger: this trigger is invoked after or before an update on some table.
Example:
CREATE TRIGGER new_employee
After UPDATE ON employee
FOR EACH ROW
Sql statement
Delete trigger: this trigger is invoked after or before an delete on some table.
Example:
CREATE TRIGGER new_employee
After DELETE ON employee
FOR EACH ROW
Sql statement

How are triggers created in MySQL?


A trigger is a set of code which is executed in response to some event.
E.g Update employee_perfomance table when a new task is inserted in task table. Here, the
trigger is update and the event is inserting a new row.
A trigger in MySQL is created using CREATE TRIGGER trigger_name. We need to specify the
trigger type.
Create trigger
Syntax:
Create trigger trigger_name
ON table_name
{
FOR [delete][update][insert]
AS
Sql statements
}
Example:
CREATE TRIGGER reminder
ON titles
FOR INSERT, UPDATE
AS some_function (50009, 16, 10)

What are the levels of triggers supported by MySQL?


A trigger is a set of code which is executed in response to some event.
E.g Update employee_perfomance table when a new task is inserted in task table. Here, the
trigger is update and the event is inserting a new row.
A trigger in MySQL is created using CREATE TRIGGER trigger_name. we need to specify the
trigger type.
1. When do you want the trigger to execute? This can be either BEFORE or AFTER

2. What do you expect the trigger to do? This can be INSERT UPDATE DELETE
3. On which table you want the trigger to run? (using ON table_name)
4. Lastly, though not mandatory, is FOR EACH ROW if it is used then the trigger will fire once for
all records of the table. If it is not specified the trigger will fire once only regardless of the
number of records being updated

How can we obtain Metadata about triggers in MySQL?

Using the show triggers statement. Show trigger lists the triggers currently defined for
tables in a database.
Example
SHOW TRIGGERS LIKE emp%\G
The Triggers table can be queried. The triggers table provides the information about the
triggers. The table has a variety of INFORMATION SCHEMA that can be queried.

Example of PHP Checkbox


each checkbox name has to be unique when you send our checkbox value in database.
HTML CODE
.........
<form action="testcheckbox.php" method="POST" name="form1">
<p>Name :
<input type="text" name="textfield">
</p>
<p>Course:
<input type="text" name="textfield">
</p>
<p>Tel No:
<input type="text" name="textfield">
</p>
<p>
<input type="checkbox" name="cd[]" value="&cent;20">
JAVA<br>
<input type="checkbox" name="cd[]" value="&cent;30">
PERL<br>
<input type="checkbox" name="cd[]" value="&cent;10">
PYTHON<br>
<input type="checkbox" name="cd[]" value="&cent;30">
C#<br>
<input type="checkbox" name="cd[]" value="&cent;90">
JYTHON<br>
<input type="checkbox" name="cd[]" value="&cent;100">
C++<br>
<input type="checkbox" name="cd[]" value="&cent;120">
PHP</p>
<p align="center">
<input type="submit" name="Submit" value="Join Now">

</p>
<p align="left"> <br>
</p>
</form>

<?php
$totalprice = 0;
foreach($cd as $cd)
$totalprice += $cd;
echo "$totalprice";
/*if(isset($_POST['$cd']))
echo 'checked';*/
?>
PHP CODE FOR ACTION

Because i get the results to be 0 always.


But i would want it to compute all the courses that would checked
and the total for their price listed.

Retrieve Data From a MySQL Database


Using PHP you can run a MySQL SELECT query to fetch the data out of the database. You have
several options in fetching information from MySQL. PHP provide several functions for this. The
first one is mysql_fetch_array()which fetch a result row as an associative array, a numeric
array, or both.
Below is an example of fetching data from MySQL, the table contact have three columns, name,
subject and message.
Example :
<?php
include 'config.php';
include 'opendb.php';
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "Name :{$row['name']} <br>" .
"Subject : {$row['subject']} <br>" .
"Message : {$row['message']} <br><br>";

}
include 'closedb.php';
?>
The while() loop will keep fetching new rows until mysql_fetch_array() returns FALSE, which
means there are no more rows to fetch. The content of the rows are assigned to the variable
$row and the values in row are then printed. Always remember to put curly brackets when you
want to insert an array value directly into a string.
In above example I use the constant MYSQL_ASSOC as the second argument to
mysql_fetch_array(), so that it returns the row as an associative array. With an
associative array you can access the field by using their name instead of using the
index . Personally I think it's more informative to use $row['subject'] instead of $row[1].
PHP also provide a function called mysql_fetch_assoc() which also return the row as an
associative array.
<?php
include 'config.php';
include 'opendb.php';
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
echo "Name :{$row['name']} <br>" .
"Subject : {$row['subject']} <br>" .
"Message : {$row['message']} <br><br>";
}
include 'closedb.php';
?>

You can also use the constant MYSQL_NUM, as the second argument to
mysql_fetch_array(). This will cause the function to return an array with numeric index.
<?php
include 'config.php';
include 'opendb.php';
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_NUM))
{
echo "Name :{$row[0]} <br>" .
"Subject : {$row[0]} <br>" .
"Message : {$row[0]} <br><br>";
}
include 'closedb.php';

?>
Using the constant MYSQL_NUM with mysql_fetch_array() gives the same result as the
function mysql_fetch_row().
There is another method for you to get the values from a row. You can use list(), to
assign a list of variables in one operation.
<?php
include 'config.php';
include 'opendb.php';
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while(list($name,$subject,$message)= mysql_fetch_row($result))
{
echo "Name :$name <br>" .
"Subject : $subject <br>" .
"Message : $row <br><br>";
}
include 'closedb.php';
?>
In above example, list() assign the values in the array returned by mysql_fetch_row()
into the variable $name, $subject and $message.
Of course you can also do it like this
<?php
include 'config.php';
include 'opendb.php';
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_row($result))
{
$name = $row[0];
$subject = $row[1];
$message = $row[2];
echo "Name :$name <br>" .
"Subject : $subject <br>" .
"Message : $row <br><br>";
}
include 'closedb.php';
?>
So you see you have lots of choices in fetching information from a database. Just

choose the one appropriate for your program

Freeing the memory ?


In some cases a query can return large result sets. As this results are stored in memory
there's a concern about memory usage. However you do not need to worry that you
will have to call this function in all your script to prevent memory congestion. In PHP all
results memory is automatically freed at the end of the script's execution.
But you are really concerned about how much memory is being used for queries that
return large result sets you can use mysql_free_result(). Calling this function will free all
memory associated with the result identifier ( $result ).
Using the above example you can call mysql_free_result() like this :
<?php
include 'config.php';
include 'opendb.php';
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_row($result))
{
...
}
mysql_free_result($result);
include 'closedb.php';
?>

Convert MySQL Query Result To Excel


Using PHP to convert MySQL query result to Excel format is also common especially in web based
finance applications. The finance data stored in database are downloaded as Excel file for easy
viewing. There is no special functions in PHP to do the job. But you can do it easily by formatting
the query result as tab separated values or put the value in an HTML table. After that set the
content type to application/vnd.ms-excel
Example : convert.php
Source : convert.php, students.txt
<?php
include 'library/config.php';
include 'library/opendb.php';
$query = "SELECT fname, lname FROM students";
$result = mysql_query($query) or die('Error, query failed');

$tsv = array();
$html = array();
while($row = mysql_fetch_array($result, MYSQL_NUM))
{
$tsv[] = implode("\t", $row);
$html[] = "<tr><td>" .implode("</td><td>", $row) .
}

"</td></tr>";

$tsv = implode("\r\n", $tsv);


$html = "<table>" . implode("\r\n", $html) . "</table>";
$fileName = 'mysql-to-excel.xls';
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$fileName");
echo $tsv;
//echo $html;
include 'library/closedb.php';
?>
In the above example $tsv is a string containing tab separated values and $html contain an
HTML table. I use implode() to join the values of $row with tab to create a tab separated string.
After the while loop implode() is used once again to join the rows using newline characters. The
headers are set and the value of $tsv is then printed. This will force the browser to save the file
as mysql-to-excel.xsl
Try running the script in your own computer then try commenting echo $tsv and uncomment
echo $html to see the difference.

How to get Query String in PHP?


s
Recently I was implementing a very basic paging system in PHP. The system also supported
search functionality, where search parameter was passed in query string, URL was looking like
this:
contactlist.php?searchText=some_search_text&pageno=2
contactlist.php is a script name
Everything that comes after ? is a query string, so in this example it will be
searchText=some_search_text&pageno=2. searchText and pageno are variables and
some_search_text and 2 are values. Query string has this form
variable1=value&variable2=value, where each variable is separated by ampersand character
(&).
In PHP we can access query string using superglobal variableRecently
In PHP we can access query string using superglobal variable $_SERVER, which is an array that
contains many useful information. To access query string, use below code:

$_SERVER['QUERY_STRING']
We should be very careful when appending new variables to query string, because as I showed
above, some time query string can be empty and sometimes it can already contains some
variables, because of this before appending new variable, we should check if we have to append
ampersand character (&) before or not. This can be done by simple if statement presented
below. Below code example also uses $_SERVER["PHP_SELF"], which returns script name
<?php
$self = $_SERVER["PHP_SELF"];
if($_SERVER["QUERY_STRING"]) {
$finalurl = $self . "?" . $_SERVER["QUERY_STRING"] .
"&myvariable=myvalue";
} else {
$finalurl = $self . "?" . "myvariable=myvalue";
}
?>
Query string can be accessed thru global array $_SERVER, more specific
$_SERVER['QUERY_STRING'] is the actual variable where query string is written, this variable
contains all data that is inputed after question mark in the URL. For example if we have URL
which looks like this:
http://someurl.com/page.php?a=1&b=2&c=3
Then echo $_SERVER['QUERY_STRING'] will display: a=1&b=2&c=3, such data is no use to us, we
need to parse it, or get it thru global array $_GET, in our case we could write:
echo $_GET['a'];
echo $_GET['b'];
echo $_GET['c'];
which would output:
1
2
3
Using $_GET array to access variables from query string is pretty simple, however we would want
to transform our URL to make it look like this:

PHP Querystring Functions


Adding and removing variables to and from URLs using PHP can be a relatively simple
process admittedly, but I have a couple of functions I use often to make the process even
less time-consuming.

Add Querystring Variable

A PHP function that will add the querystring variable $key with a value $value to $url. If $key is
already specified within $url, it will replace it.
plainpop-up
1. function add_querystring_var($url, $key, $value) {
2.
$url = preg_replace('/(.*)(?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
3.
$url = substr($url, 0, -1);
4.
if (strpos($url, '?') === false) {
5.
return ($url . '?' . $key . '=' . $value);
6.
} else {
7.
return ($url . '&' . $key . '=' . $value);
8.
}
9. }

Remove Querystring Variable


A PHP function that will remove the variable $key and its value from the given $url.
plainpop-up
1. function remove_querystring_var($url, $key) {
2.
$url = preg_replace('/(.*)(?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
3.
$url = substr($url, 0, -1);
4.
return ($url);
5. }

How to use the query string in PHP


This article tells you how to pass variables to a PHP page using the query string, and how to
access them from that page. Have you ever seen a URL which looked like
"www.example.com/pag e.php?mode=1&style=red"? Well, this page is being passed variables
and their values through the query string, here the variables "mode" and "style" are being
passed, with values "1" and "red" respectively. The question mark indicates the start of the query
string and the ampersand, &, symbol seperates variable=value assignments

FOREACH Loop
FOREACH is used in PHP to loop over all elements of an array. The basic syntax of FOREACH is as
follows:
FOREACH ($array_variable as $value)
{
[code to execute]
}
or
FOREACH ($array_variable as $key => $value)
{
[code to execute]
}

In both cases, the number of times [code to execute] will be executed is equal to the number of
elements in the $array_variable array.
Let's look at an example. Assuming we have the following piece of code:

$array1 = array(1,2,3,4,5);
FOREACH ($array1 as $abc)
{
print "new value is " . $abc*10 . "<br>";
}
The output of the above code is:

new
new
new
new
new

value
value
value
value
value

is
is
is
is
is

10
20
30
40
50

The FOREACH loop above went through all 5 elements of array $array1, and each time prints out
a statement containing 10x the array element value.

PHP : $_SERVER
$_SERVER has following basic properties:
1. Set by web server.
2. Directly related to the runtime environment of the current php script.
3. It does the same job as $HTTP_SERVER_VARS used to do in previous versions of PHP
Here we discuss the elements which can exist within the $_SERVER.

PHP : $_SERVER['PHP_SELF']
You can find the filename of the currently executing script by using $_SERVER['PHP_SELF'].
Filename shown as output is relative to the root of the document.
Following php code used $_SERVER['PHP_SELF']
<?php
echo $SERVER['PHP_SELF'];
?>

View the example of $_SERVER PHP_SELF in browser


Another advanced example:

Basic knowledge of array is a prerequisite of this example. You can get back to this
example after you learn php array. The following PHP code compares the array elements
with the $_SERVER['PHP_SELF'] and displays a message.
<?php
$findit=array('/php/super-variables/test.php',
'/php/super-variables/test1123.php',
'/php/super-variables/php-self-advanced-example1.php'
);
for ($j=0; $j<count($findit); $j++)
{
if ($_SERVER['PHP_SELF']==$findit[$j])
echo "You are learning PHP Super Globals";
}
?>

$_ENV, the Environment variable array is empty in PHP


The environment variables are usually made available to your scripts via $_ENV, just like $_POST,
$_GET etc. are. It seems however that the registration by PHP of these kind of variables for use in
your scripts is governed by a configuration option called variables_order in the php.ini file. By
default many of the latest installs (and associated php.inis) of PHP will have this option set to
GPCS, which stands for Get, Post, Cookie and Built-in variables respectively.
Therefore if you find your php_info() function call returning a bucket load of environment related
information but yet a print_r($_ENV) returns an empty array () check the aforementioned setting
and be sure to add E in there somewhere so as to instruct PHP to make environment variables
available to you and your scripts.
While Im not 100% certain I believe the ordering of the letters is only important when you have
the register_globals option set to on. If register_globals is set to on (off by default since 4.2 and
ditched in 6.0) then PHP will make all the variable kinds (Post, Get etc.) specified in
variables_order available as global variables in the order you specified in that directive. Imagine
for instance that you have EGP specified in variables_order and register_globals set to on, if you
have a variable called Path in both the $_ENV and $_POST arrays, the value from the post array
will overwrite the value from the environment array and thus the global variable $Path will hold
information from $_POST and not $_ENV. If register_globals was turned to off, you would simply
access all array indexes by their full name such as $_ENV["Path"] and $_POST["Path"] and thus
they will be considered as 100%

POST without submit button


I believe JavaScript's form object has a method to submit a form (thus submitting without a
button-click), but if I understood your post correctly, you don't even want a form there - in that
case, you can use cURL library. This allows you to set $_POST without going through an HTML
form (and way more than that). Some familiarity with HTTP will definitely be a help in using cURL.
I'm nopt an expert on this, so if you are interested, check these out:
<script language="javascript">
<!-function mySubmit() {

document.formName.submit();
}
// -->
</script>
<form name="formName" action="url" method="post">
<a href="javascript:mySubmit()>Submit Me</a>
</form>

PHP Cookies
A cookie is often used to identify a user.

What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.
How to Create a Cookie?
The setcookie() function is used to set a cookie.
Note: The setcookie() function must appear BEFORE the <html> tag.
Syntax
setcookie(name, value, expire, path, domain);
Example 1
In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to
it. We also specify that the cookie should expire after one hour:
<?php
setcookie("user", "Alex Porter", time()+3600);
?>
<html>
.....
Note: The value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
Example 2
You can also set the expiration time of the cookie in another way. It may be easier than using
seconds.
<?php
$expire=time()+60*60*24*30;

setcookie("user", "Alex Porter", $expire);


?>
<html>
.....
In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30
days).
How to Retrieve a Cookie Value?
The PHP $_COOKIE variable is used to retrieve a cookie value.
In the example below, we retrieve the value of the cookie named "user" and display it on a page:
<?php
// Print a cookie
echo $_COOKIE["user"];
// A way to view all cookies
print_r($_COOKIE);
?>
In the following example we use the isset() function to find out if a cookie has been set:
<html>
<body>
<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
echo "Welcome guest!<br />";
?>
</body>
</html>
How to Delete a Cookie?
When deleting a cookie you should assure that the expiration date is in the past.
Delete example:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>

What if a Browser Does NOT Support Cookies?

If your application deals with browsers that do not support cookies, you will have to use other
methods to pass information from one page to another in your application. One method is to
pass the data through forms (forms and user input are described earlier in this tutorial).
The form below passes the user input to "welcome.php" when the user clicks on the "Submit"
button:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
Retrieve the values in the "welcome.php" file like this:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>

include()
The include() statement includes and evaluates the specified file.

The documentation below also applies to require().


Files are included based on the file path given or, if none is given, the include_path specified. If
the file isn't found in the include_path, include() will finally check in the calling script's own
directory and the current working directory before failing. The include() construct will emit a
warning if it cannot find a file; this is different behavior from require(), which will emit a fatal
error.
If a path is defined whether absolute (starting with a drive letter or \ on Windows, or / on
Unix/Linux systems) or relative to the current directory (starting with . or ..) the include_path
will be ignored altogether. For example, if a filename begins with ../, the parser will look in the
parent directory to find the requested file.

For more information on how PHP handles including files and the include path, see the
documentation for include_path.

When a file is included, the code it contains inherits the variable scope of the line on which the
include occurs. Any variables available at that line in the calling file will be available within the
called file, from that point forward. However, all functions and classes defined in the included file
have the global scope.

Example #1 Basic include() example


vars.php
<?php
$color = 'green';
$fruit = 'apple';
?>
test.php
<?php
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A green apple
?>

If the include occurs inside a function within the calling file, then all of the code contained in the
called file will behave as though it had been defined inside that function. So, it will follow the
variable scope of that function. An exception to this rule are magic constants which are
evaluated by the parser before the include occurs.

Example #2 Including within functions


<?php
function foo()
{
global $color;
include 'vars.php';
echo "A $color $fruit";
}
/* vars.php is in the scope of foo() so
*
* $fruit is NOT available outside of this *
* scope. $color is because we declared it *
* as global.
*/
foo();
// A green apple
echo "A $color $fruit"; // A green

?>

PHP Include File


Server Side Includes (SSI)
You can insert the content of one PHP file into another PHP file before the server executes it, with
the include() or require() function.
The two functions are identical in every way, except how they handle errors:

include() generates a warning, but the script will continue execution


require() generates a fatal error, and the script will stop

These two functions are used to create functions, headers, footers, or elements that will be
reused on multiple pages.
Server side includes saves a lot of work. This means that you can create a standard header,
footer, or menu file for all your web pages. When the header needs to be updated, you can only
update the include file, or when you add a new page to your site, you can simply change the
menu file (instead of updating the links on all your web pages).

PHP include() Function


The include() function takes all the content in a specified file and includes it in the current file.
If an error occurs, the include() function generates a warning, but the script will continue
execution.
Example 1
Assume that you have a standard header file, called "header.php". To include the header file in a
page, use the include() function:
<html>
<body>
<?php include("header.php"); ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>
Example 2
Assume we have a standard menu file, called "menu.php", that should be used on all pages:
<a
<a
<a
<a

href="/default.php">Home</a>
href="/tutorials.php">Tutorials</a>
href="/references.php">References</a>
href="/examples.php">Examples</a>

<a href="/about.php">About Us</a>


<a href="/contact.php">Contact Us</a>
All pages in the Web site should include this menu file. Here is how it can be done:
<html>
<body>
<div class="leftmenu">
<?php include("menu.php"); ?>
</div>
<h1>Welcome to my home page.</h1>
<p>Some text.</p>
</body>
</html>
If you look at the source code of the page above (in a browser), it will look like this:
<html>
<body>
<div class="leftmenu">
<a href="/default.php">Home</a>
<a href="/tutorials.php">Tutorials</a>
<a href="/references.php">References</a>
<a href="/examples.php">Examples</a>
<a href="/about.php">About Us</a>
<a href="/contact.php">Contact Us</a>
</div>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>

PHP Tools
Here is some PHP information that you may find useful.
Dynamic Site Map with PHP

Script: This is a script, written in PHP, that will generate a site map based on the directory
structure of the site. You can easily exclude files and/or directories.
Forcing a Download Dialog

A fairly common question is, "How can I force a file to download to the user?" The answer
is, you really cannot. What you can do is force a download dialog box that gives the user a
choice to open or save a linked file, or to cancel the request.
Form to E-mail Processing

Tutorial: A tutorial on how you can use PHP to process form submissions and send the
results to an e-mail address.
Multiple Page Forms

Tutorial: So you have this long, involved form. Rather than present the user with a myriad
of inputs on a single page, you want to break this up into separate form pages. So now
you're asking, "How do you make multiple page forms?"
Processing XML/RSS with PHP

In the beginning, the Internet was a simple mechanism for exchanging text data. Various
markup tags were devised to represent various levels of text headings, paragraphs, lists,
etc. At that time, those tags were sufficient to represent the data being exchanged. Now,
more types of data are being represented and that data is being displayed on a variety of
devices, not just visual web browsers.
Send a Link to a Friend

Script: Ready to run form that will allow you to put a link on your page to send a link to a
friend.
Setting up a virtual host in Apache

Tutorial: Setting up a virtual host in the Apache web server is not exactly a PHP topic, but
many PHP developers use the Apache web server to test web pages on their development
machine.

PHP require() Function


The require() function is identical to include(), except that it handles errors differently.
If an error occurs, the include() function generates a warning, but the script will continue
execution. The require() generates a fatal error, and the script will stop.
Error Example include() Function
<html>
<body>
<?php
include("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>

Error message:
Warning: include(wrongFile.php) [function.include]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5
Warning: include() [function.include]:
Failed opening 'wrongFile.php' for inclusion
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5
Hello World!
Notice that the echo statement is executed! This is because a Warning does not stop the script
execution.
Error Example require() Function
Now, let's run the same example with the require() function.
<html>
<body>
<?php
require("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>
Error message:
Warning: require(wrongFile.php) [function.require]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5
Fatal error: require() [function.require]:
Failed opening required 'wrongFile.php'
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5
The echo statement is not executed, because the script execution stopped after the fatal error.
It is recommended to use the require() function instead of include(), because scripts should not
continue after an error.

How to typeset an underscore character


The underscore character _ is ordinarily used in TeX to indicate a subscript in maths mode; if
you type _, on its own, in the course of ordinary text, TeX will complain. The proper LaTeX
command for underscore is \textunderscore, but the LaTeX 2.09 command \_ is an established

alias. Even so, if youre writing a document which will contain a large number of underscore
characters, the prospect of typing \_ for every one of them will daunt most ordinary people.
Moderately skilled macro programmers can readily generate a quick hack to permit typing _ to
mean text underscore (the answer in defining characters as macros uses this example to
illustrate its techniques). However, the code is somewhat tricky, and more importantly there are
significant points where its easy to get it wrong. There is therefore a package underscore which
provides a general solution to this requirement.
There is a problem, though: OT1 text fonts dont contain an underscore character, unless theyre
in the typewriter version of the encoding (used by fixed-width fonts such as cmtt). In place of
such a character, LaTeX (in OT1 encoding) uses a short rule for the command \textunderscore, but
this poses problems for systems that interpret PDF for example those PDF-to-voice systems
used by those who find reading difficult.
So either you must ensure that your underscore characters only occur in text set in a typewriter
font, or you must use a more modern encoding, such as T1, which has the same layout for every
font, and thus an underscore in every font.
A stable procedure to achieve this is:
% (1) choose a font that is available as T1
% for example:
\usepackage{lmodern}
% (2) specify encoding
\usepackage[T1]{fontenc}
% (3) load symbol definitions
\usepackage{textcomp}
which will provide a command \textunderscore which robustly selects the right character. The
underscore package, mentioned above, will use this command.

What is Localhost?
"Localhost" refers to the local computer that a program is running on. For example, if you are running a
Web browser on your computer, your computer is considered to be the "localhost." While this does not
need to be specified when using a single computer, the localhost does need to be defined when running
programs from multiple computers. For example, a network administrator might use his local machine to
start a Web server on one system and use a remote access program on another. These programs would
run from computers other than the localhost.
In the example above, the two non-local computers must be defined by their IP addresses. The local
machine is defined as "localhost," which gives it an IP address of 127.0.0.1. This is considered a
"loopback" address because the information sent to it is routed back to the local machine. Localhost is
often used in Web scripting languages like PHP and ASP when defining what server the code should run
from or where a database is located.

Why are use enctype in form?

enctype is an abbreviation of 'encoding type', it is used to tell the browser the MIME type of the
data being transferred, the default MIME type is 'application/x-www-form-urlencoded' and is not
even necessary to input, but if the form type is uploading an image or another media type then
the 'enctype' will have to be set for media encoding, 'multipart/form-data'.

PHP $_GET Function


The built-in $_GET function is used to collect values in a form with method="get".

The $_GET Function


The built-in $_GET function is used to collect values from a form sent with method="get".
Information sent from a form with the GET method is visible to everyone (it will be displayed in
the browser's address bar) and has limits on the amount of information to send.
Example
<form action="welcome.php" method="get">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
When the user clicks the "Submit" button, the URL sent to the server could look something like
this:
http://www.w3schools.com/welcome.php?fname=Peter&age=37
The "welcome.php" file can now use the $_GET function to collect form data (the names of the
form fields will automatically be the keys in the $_GET array):
Welcome <?php echo $_GET["fname"]; ?>.<br />
You are <?php echo $_GET["age"]; ?> years old!

When to use method="get"?


When using method="get" in HTML forms, all variable names and values are displayed in the
URL.
Note: This method should not be used when sending passwords or other sensitive information!
However, because the variables are displayed in the URL, it is possible to bookmark the page.
This can be useful in some cases.
Note: The get method is not suitable for very large variable values. It should not be used with
values exceeding 2000 characters.

HTML Code Excerpt:

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


<select name="item">
...<input name="quantity" type="text" />

The get method is different in that it passes the variables along to the "process.php" web page
by appending them onto the end of the URL. The URL, after clicking submit, would have this
added on to the end of it:
"?item=##&quantity=##"
The question mark "?" tells the browser that the following items are variables. Now that we
changed the method of sending information on "order.html", we must change the "process.php"
code to use the "$_GET" associative array.

PHP Code Excerpt:


$quantity = $_GET['quantity'];
$item = $_GET['item'];

After changing the array name the script will function properly. Using the get method displays the
variable information to your visitor, so be sure you are not sending password information or other
sensitive items with the get method. You would not want your visitors seeing something they are
not supposed to!

PHP $_POST Function


The built-in $_POST function is used to collect values in a form with method="post".

The $_POST Function


The built-in $_POST function is used to collect values from a form sent with method="post".
Information sent from a form with the POST method is invisible to others and has no limits on the
amount of information to send.
Note: However, there is an 8 Mb max size for the POST method, by default (can be changed by
setting the post_max_size in the php.ini file).

Example
<form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
When the user clicks the "Submit" button, the URL will look like this:

http://www.w3schools.com/welcome.php
The "welcome.php" file can now use the $_POST function to collect form data (the names of the
form fields will automatically be the keys in the $_POST array):
Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old.

When to use method="post"?


Information sent from a form with the POST method is invisible to others and has no limits on the
amount of information to send.
However, because the variables are not displayed in the URL, it is not possible to bookmark the
page.

POST - Review
In our PHP Forms Lesson we used the post method. This is what the pertinent line of HTML code
looked like:

HTML Code Excerpt:


<form action="process.php" method="post">
<select name="item">
...
<input name="quantity" type="text" />

This HTML code specifies that the form data will be submitted to the "process.php" web page
using the POST method. The way that PHP does this is to store all the "posted" values into an
associative array called "$_POST". Be sure to take notice the names of the form data names, as
they represent the keys in the "$_POST" associative array.
Now that you know about associative arrays, the PHP code from "process.php" should make a
litte more sense.

PHP Code Excerpt:


$quantity = $_POST['quantity'];
$item = $_POST['item'];

The form names are used as the keys in the associative array, so be sure that you never have
two input items in your HTML form that have the same name. If you do, then you might see some
problems arise.

The PHP $_REQUEST Function


The PHP built-in $_REQUEST function contains the contents of both $_GET, $_POST, and
$_COOKIE.
The $_REQUEST function can be used to collect form data sent with both the GET and POST
methods.

Example
Welcome <?php echo $_REQUEST["fname"]; ?>!<br />
You are <?php echo $_REQUEST["age"]; ?> years old.

PHP String Functions

PHP String Introduction


The string functions allow you to manipulate strings.
PHP String Functions
PHP: indicates the earliest version of PHP that supports the function.
Function

Description

PHP

addcslashes()

Returns a string with backslashes in front of the


specified characters

addslashes()

Returns a string with backslashes in front of predefined 3


characters

bin2hex()

Converts a string of ASCII characters to hexadecimal


values

chop()

Alias of rtrim()

chr()

Returns a character from a specified ASCII value

chunk_split()

Splits a string into a series of smaller parts

convert_cyr_string()

Converts a string from one Cyrillic character-set to


another

convert_uudecode()

Decodes a uuencoded string

convert_uuencode()

Encodes a string using the uuencode algorithm

count_chars()

Returns how many times an ASCII character occurs


within a string and returns the information

crc32()

Calculates a 32-bit CRC for a string

crypt()

One-way string encryption (hashing)

echo()

Outputs strings

explode()

Breaks a string into an array

fprintf()

Writes a formatted string to a specified output stream

get_html_translation_table()

Returns the translation table used by


htmlspecialchars() and htmlentities()

hebrev()

Converts Hebrew text to visual text

hebrevc()

Converts Hebrew text to visual text and new lines (\n)


into <br />

html_entity_decode()

Converts HTML entities to characters

htmlentities()

Converts characters to HTML entities

htmlspecialchars_decode()

Converts some predefined HTML entities to characters 5

htmlspecialchars()

Converts some predefined characters to HTML entities 3

implode()

Returns a string from the elements of an array

join()

Alias of implode()

levenshtein()

Returns the Levenshtein distance between two strings 3

localeconv()

Returns locale numeric and monetary formatting


information

ltrim()

Strips whitespace from the left side of a string

md5()

Calculates the MD5 hash of a string

md5_file()

Calculates the MD5 hash of a file

metaphone()

Calculates the metaphone key of a string

money_format()

Returns a string formatted as a currency string

nl_langinfo()

Returns specific local information

nl2br()

Inserts HTML line breaks in front of each newline in a


string

number_format()

Formats a number with grouped thousands

ord()

Returns the ASCII value of the first character of a string 3

parse_str()

Parses a query string into variables

print()

Outputs a string

printf()

Outputs a formatted string

quoted_printable_decode()

Decodes a quoted-printable string

quotemeta()

Quotes meta characters

rtrim()

Strips whitespace from the right side of a string

setlocale()

Sets locale information

sha1()

Calculates the SHA-1 hash of a string

sha1_file()

Calculates the SHA-1 hash of a file

similar_text()

Calculates the similarity between two strings

soundex()

Calculates the soundex key of a string

sprintf()

Writes a formatted string to a variable

sscanf()

Parses input from a string according to a format

str_ireplace()

Replaces some characters in a string (case-insensitive) 5

str_pad()

Pads a string to a new length

str_repeat()

Repeats a string a specified number of times

str_replace()

Replaces some characters in a string (case-sensitive)

str_split()

Splits a string into an array

str_word_count()

Count the number of words in a string

strcasecmp()

Compares two strings (case-insensitive)

strchr()

Finds the first occurrence of a string inside another


string (alias of strstr())

strcmp()

Compares two strings (case-sensitive)

strcoll()

Locale based string comparison

strcspn()

Returns the number of characters found in a string


3
before any part of some specified characters are found

strip_tags()

Strips HTML and PHP tags from a string

stripcslashes()

Unquotes a string quoted with addcslashes()

stripslashes()

Unquotes a string quoted with addslashes()

stripos()

Returns the position of the first occurrence of a string


inside another string (case-insensitive)

stristr()

Finds the first occurrence of a string inside another


string (case-insensitive)

strlen()

Returns the length of a string

strnatcasecmp()

Compares two strings using a "natural order" algorithm 4


(case-insensitive)

strnatcmp()

Compares two strings using a "natural order" algorithm 4


(case-sensitive)

strncasecmp()

String comparison of the first n characters (caseinsensitive)

strncmp()

String comparison of the first n characters (casesensitive)

strpbrk()

Searches a string for any of a set of characters

strpos()

Returns the position of the first occurrence of a string


inside another string (case-sensitive)

strrchr()

Finds the last occurrence of a string inside another


string

strrev()

Reverses a string

strripos()

Finds the position of the last occurrence of a string


inside another string (case-insensitive)

strrpos()

Finds the position of the last occurrence of a string


inside another string (case-sensitive)

strspn()

Returns the number of characters found in a string that 3


contains only characters from a specified charlist

strstr()

Finds the first occurrence of a string inside another


string (case-sensitive)

strtok()

Splits a string into smaller strings

strtolower()

Converts a string to lowercase letters

strtoupper()

Converts a string to uppercase letters

strtr()

Translates certain characters in a string

substr()

Returns a part of a string

substr_compare()

Compares two strings from a specified start position


(binary safe and optionally case-sensitive)

substr_count()

Counts the number of times a substring occurs in a


string

substr_replace()

Replaces a part of a string with another string

trim()

Strips whitespace from both sides of a string

ucfirst()

Converts the first character of a string to uppercase

ucwords()

Converts the first character of each word in a string to 3


uppercase

vfprintf()

Writes a formatted string to a specified output stream

vprintf()

Outputs a formatted string

vsprintf()

Writes a formatted string to a variable

PHP Array Functions


PHP: indicates the earliest version of PHP that supports the function.
Function

Description

PHP

array()

Creates an array

array_change_key_case()

Returns an array with all keys in lowercase or uppercase

array_chunk()

Splits an array into chunks of arrays

array_combine()

Creates an array by using one array for keys and another 5


for its values

array_count_values()

Returns an array with the number of occurrences for each 4


value

array_diff()

Compares array values, and returns the differences

array_diff_assoc()

Compares array keys and values, and returns the


differences

array_diff_key()

Compares array keys, and returns the differences

array_diff_uassoc()

Compares array keys and values, with an additional user- 5

made function check, and returns the differences


array_diff_ukey()

Compares array keys, with an additional user-made


function check, and returns the differences

array fill()

Fills an array with values

array filter()

Filters elements of an array using a user-made function

array flip()

Exchanges all keys with their associated values in an array 4

array intersect()

Compares array values, and returns the matches

array_intersect_assoc()

Compares array keys and values, and returns the matches 4

array_intersect_key()

Compares array keys, and returns the matches

array_intersect_uassoc()

Compares array keys and values, with an additional user- 5


made function check, and returns the matches

array_intersect_ukey()

Compares array keys, with an additional user-made


function check, and returns the matches

array_key_exists()

Checks if the specified key exists in the array

array_keys()

Returns all the keys of an array

array_map()

Sends each value of an array to a user-made function,


which returns new values

array_merge()

Merges one or more arrays into one array

array_merge_recursive()

Merges one or more arrays into one array

array_multisort()

Sorts multiple or multi-dimensional arrays

array_pad()

Inserts a specified number of items, with a specified value, 4


to an array

array_pop()

Deletes the last element of an array

array_product()

Calculates the product of the values in an array

array_push()

Inserts one or more elements to the end of an array

array_rand()

Returns one or more random keys from an array

array_reduce()

Returns an array as a string, using a user-defined function 4

array_reverse()

Returns an array in the reverse order

array_search()

Searches an array for a given value and returns the key

array_shift()

Removes the first element from an array, and returns the 4


value of the removed element

array_slice()

Returns selected parts of an array

array_splice()

Removes and replaces specified elements of an array

array_sum()

Returns the sum of the values in an array

array_udiff()

Compares array values in a user-made function and


returns an array

array_udiff_assoc()

Compares array keys, and compares array values in a


user-made function, and returns an array

array_udiff_uassoc()

Compares array keys and array values in user-made


functions, and returns an array

array_uintersect()

Compares array values in a user-made function and


returns an array

array_uintersect_assoc()

Compares array keys, and compares array values in a

4
5

user-made function, and returns an array


array_uintersect_uassoc()

Compares array keys and array values in user-made


functions, and returns an array

array_unique()

Removes duplicate values from an array

array_unshift()

Adds one or more elements to the beginning of an array

array_values()

Returns all the values of an array

array_walk()

Applies a user function to every member of an array

array_walk_recursive()

Applies a user function recursively to every member of an 5


array

arsort()

Sorts an array in reverse order and maintain index


association

asort()

Sorts an array and maintain index association

compact()

Create array containing variables and their values

count()

Counts elements in an array, or properties in an object

current()

Returns the current element in an array

each()

Returns the current key and value pair from an array

end()

Sets the internal pointer of an array to its last element

extract()

Imports variables into the current symbol table from an


array

in_array()

Checks if a specified value exists in an array

key()

Fetches a key from an array

krsort()

Sorts an array by key in reverse order

ksort()

Sorts an array by key

list()

Assigns variables as if they were an array

natcasesort()

Sorts an array using a case insensitive "natural order"


algorithm

natsort()

Sorts an array using a "natural order" algorithm

next()

Advance the internal array pointer of an array

pos()

Alias of current()

prev()

Rewinds the internal array pointer

range()

Creates an array containing a range of elements

reset()

Sets the internal pointer of an array to its first element

rsort()

Sorts an array in reverse order

shuffle()

Shuffles an array

sizeof()

Alias of count()

sort()

Sorts an array

uasort()

Sorts an array with a user-defined function and maintain


index association

uksort()

Sorts an array by keys using a user-defined function

usort()

Sorts an array by values using a user-defined function

PHP Date / Time Functions

PHP Date / Time Introduction


The date/time functions allow you to extract and format the date and time on the server.
Note: These functions depend on the locale settings of the server!
functions.

Runtime Configuration
The behavior of the date/time functions is affected by settings in php.ini.
Date/Time configuration options:
Name

Default

Description

Changeable

date.default_latitu "31.7667"
de

Specifies the default latitude (available


since PHP 5). This option is used by
date_sunrise() and date_sunset()

PHP_INI_ALL

date.default_longit "35.2333"
ude

Specifies the default longitude (available PHP_INI_ALL


since PHP 5). This option is used by
date_sunrise() and date_sunset()

date.sunrise_zenit "90.83"
h

Specifies the default sunrise zenith


(available since PHP 5). This option is
used by date_sunrise() and
date_sunset()

PHP_INI_ALL

date.sunset_zenith "90.83"

Specifies the default sunset zenith


(available since PHP 5). This option is
used by date_sunrise() and
date_sunset()

PHP_INI_ALL

date.timezone

Specifies the default timezone (available PHP_INI_ALL


since PHP 5.1)

""

PHP Date / Time Functions


PHP: indicates the earliest version of PHP that supports the function.
Function

Description

PHP

checkdate()

Validates a Gregorian date

date_default_timezone_get()

Returns the default time zone

date_default_timezone_set()

Sets the default time zone

date_sunrise()

Returns the time of sunrise for a given day / location

date_sunset()

Returns the time of sunset for a given day / location

date()

Formats a local time/date

getdate()

Returns an array that contains date and time


information for a Unix timestamp

gettimeofday()

Returns an array that contains current time information 3

gmdate()

Formats a GMT/UTC date/time

gmmktime()

Returns the Unix timestamp for a GMT date

gmstrftime()

Formats a GMT/UTC time/date according to locale


settings

idate()

Formats a local time/date as integer

localtime()

Returns an array that contains the time components of 4


a Unix timestamp

microtime()

Returns the microseconds for the current time

mktime()

Returns the Unix timestamp for a date

strftime()

Formats a local time/date according to locale settings

strptime()

Parses a time/date generated with strftime()

strtotime()

Parses an English textual date or time into a Unix


timestamp

time()

Returns the current time as a Unix timestamp

PHP Directory Functions


PHP Directory Introduction
The directory functions allow you to retrieve information about directories and their contents.

PHP Directory Functions


PHP: indicates the earliest version of PHP that supports the function.

Function

Description

PHP

chdir()

Changes the current directory

chroot()

Changes the root directory of the current process

dir()

Opens a directory handle and returns an object

closedir()

Closes a directory handle

getcwd()

Returns the current directory

opendir()

Opens a directory handle

readdir()

Returns an entry from a directory handle

rewinddir()

Resets a directory handle

scandir()

Lists files and directories inside a specified path

PHP Error and Logging Functions


PHP Error and Logging Introduction
The error and logging functions allows error handling and logging.
The error functions allow users to define error handling rules, and modify the way the errors can
be logged.
The logging functions allow users to log applications and send log messages to email, system
logs or other machines..
PHP that supports the function.
Function

Description

PHP

debug_backtrace()

Generates a backtrace

debug_print_backtrace()

Prints a backtrace

error_get_last()

Gets the last error occurred

error_log()

Sends an error to the server error-log, to a file or to a 4


remote destination

error_reporting()

Specifies which errors are reported

restore_error_handler()

Restores the previous error handler

restore_exception_handler()

Restores the previous exception handler

set_error_handler()

Sets a user-defined function to handle errors

set_exception_handler()

Sets a user-defined function to handle exceptions

trigger_error()

Creates a user-defined error message

user_error()

Alias of trigger_error()

PHP Error and Logging Constants


PHP: indicates the earliest version of PHP that supports the constant.
Valu Constant
e

Description

PHP

E_ERROR

Fatal run-time errors. Errors that cannot be recovered


from. Execution of the script is halted

E_WARNING

Non-fatal run-time errors. Execution of the script is


not halted

E_PARSE

Compile-time parse errors. Parse errors should only


be generated by the parser

E_NOTICE

Run-time notices. The script found something that


might be an error, but could also happen when
running a script normally

16

E_CORE_ERROR

Fatal errors at PHP startup. This is like an E_ERROR in 4


the PHP core

32

E_CORE_WARNING

Non-fatal errors at PHP startup. This is like an


E_WARNING in the PHP core

64

E_COMPILE_ERROR

Fatal compile-time errors. This is like an E_ERROR


generated by the Zend Scripting Engine

128 E_COMPILE_WARNING

Non-fatal compile-time errors. This is like an


4
E_WARNING generated by the Zend Scripting Engine

256 E_USER_ERROR

Fatal user-generated error. This is like an E_ERROR


set by the programmer using the PHP function
trigger_error()

512 E_USER_WARNING

Non-fatal user-generated warning. This is like an


E_WARNING set by the programmer using the PHP

function trigger_error()
1024 E_USER_NOTICE

User-generated notice. This is like an E_NOTICE set


by the programmer using the PHP function
trigger_error()

2048 E_STRICT

Run-time notices. PHP suggest changes to your code 5


to help interoperability and compatibility of the code

4096 E_RECOVERABLE_ERROR

Catchable fatal error. This is like an E_ERROR but can 5


be caught by a user defined handle (see also
set_error_handler())

6143 E_ALL

All errors and warnings, except of level E_STRICT

PHP Functions
The real power of PHP comes from its functions.
In PHP, there are more than 700 built-in functions.

PHP Built-in Functions


For a complete reference and examples of the built-in functions, please visit our.

PHP Functions
In this chapter we will show you how to create your own functions.
To keep the script from being executed when the page loads, you can put it into a function.
A function will be executed by a call to the function.
You may call a function from anywhere within a page.

Create a PHP Function


A function will be executed by a call to the function.
Syntax
function functionName()
{
code to be executed;
}
PHP function guidelines:
Give the function a name that reflects what the function does
The function name can start with a letter or underscore (not a number)
Example
A simple function that writes my name when it is called:
<html>

<body>
<?php
function writeName()
{
echo "Kai Jim Refsnes";
}
echo "My name is ";
writeName();
?>
</body>
</html>
Output:
My name is Kai Jim Refsnes

PHP Functions - Adding parameters


To add more functionality to a function, we can add parameters. A parameter is just like a
variable.
Parameters are specified after the function name, inside the parentheses.
Example 1
The following example will write different first names, but equal last name:
<html>
<body>
<?php
function writeName($fname)
{
echo $fname . " Refsnes.<br />";
}
echo "My name is ";
writeName("Kai Jim");
echo "My sister's name is ";
writeName("Hege");
echo "My brother's name is ";
writeName("Stale");
?>
</body>
</html>
Output:
My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes.
My brother's name is Stale Refsnes.
Example 2
The following function has two parameters:

<html>
<body>
<?php
function writeName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "<br />";
}
echo "My name is ";
writeName("Kai Jim",".");
echo "My sister's name is ";
writeName("Hege","!");
echo "My brother's name is ";
writeName("Stle","?");
?>
</body>
</html>
Output:
My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes!
My brother's name is Stle Refsnes?

PHP Functions - Return values


To let a function return a value, use the return statement.

Example
<html>
<body>
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>

output
1 + 16 = 17

Print_r () PHP Function


Definition: The Print_r () PHP function is used to return an array in a human readable form. It is
simply written as Print_r ($your_array)
Also Known As: Print Array
Examples:
<?php

$Names = array ('a' => 'Angela', 'b' => 'Bradley', 'c' => array ('Cade', 'Caleb'));
print_r ($Names);
?>
The results would be something like:
Array
(
[a] => Angela
[b] => Bradley
[c] => Array
(
[0] => Cade
[1] => Caleb
)
)

HOW TO USE THE trim() FUNCTION IN PHP


The trim() function strips specified characters from beginning and end of a string. It takes two
parameters: the string to perform the action on and the specified character/s to strip out from
the beginning and end of that string.
If the characters to strip are not specified, then trim() strips all whitespace (" "), new line "\n", tab
("\t"), carriage return ("\r") by default.
Example:
$string=" John James was here ";
$newstring=trim($string);
echo $newstring;
The above will output: John James was here
This is a good function to use when, for example, a user enters something in the input field of a
site form but mistakenly leaves a whitespace before the actual entry. Technically, whitespace
John is not the same as John as whitespace is considered a character as well.
You can also specify what character/s to strip from the beginning and end of a string.

Example:
$string="eggs sold here";
$newstring=trim($string,"e");
echo $newstring;
The above will output: ggs sold her
The e at the beginning of the string and the e at the end of the string are stripped out.
Say you only want to strip the e at the right (ie. at the end of the string), then use:
$string="eggs sold here";
$newstring=rtrim($string,"e"); // right trim
echo $newstring;
The above will output: eggs sold her
Say you only want to strip the e at the left (ie. at the start of the string), then use:
$string="eggs sold here";
$newstring=ltrim($string,"e"); // left trim
echo $newstring;
The above will output: ggs sold here

PHP implode() Function


Definition and Usage
The implode() function returns a string from the elements of an array.
Syntax
implode(separator,array)

Parameter

Description

separator

Optional. Specifies what to put between the array elements. Default is "" (an
empty string)

array

Required. The array to join to a string

Tips and Notes


Note: The implode() function accept its parameters in either order. However, for consistency
with explode(), you should use the documented order of arguments.
Note: The separator parameter of implode() is optional. However, it is recommended to always
use two parameters for backwards compatibility.
Example
<?php
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);
?>
The output of the code above will be:
Hello World! Beautiful Day!

PHP - Array implode


The PHP function implode operates on an array and is known as the "undo" function of explode. If
you have used explode to break up a string into chunks or just have an array of stuff you can use
implode to put them all into one string.

PHP implode - Repairing the Damage


The first argument of implode is the string of characters you want to use to join the array pieces
together. The second argument is the array (pieces).
PHP Code:
$pieces = array("Hello", "World,", "I", "am", "Here!");
$gluedTogetherSpaces = implode(" ", $pieces);
$gluedTogetherDashes = implode("-", $pieces);
for($i = 0; $i < count($pieces); $i++){
echo "Piece #$i = $pieces[$i] <br />";
}
echo "Glued with Spaces = $gluedTogetherSpaces <br />";
echo "Glued with Dashes = $gluedTogetherDashes";
Display:
Piece #0 = Hello
Piece #1 = World,
Piece #2 = I
Piece #3 = am
Piece #4 = Here!
Glued with Spaces = Hello World, I am Here!
Glued with Dashes = Hello-World,-I-am-Here!

The implode function will convert the entire array into a string and there is no optional argument
to limit this as there was in the explode function.

HOW TO USE THE explode() FUNCTION IN PHP


The explode function explodes a string into substrings. It takes two arguments, the separator and
the string to be exploded. It returns an array of substrings between the separators.
Example 1:
$fullstring="My-name-is-John";
$newstring=explode("-",$fullstring);
This results in an array of 4 elements, each part a substring and each part separated by the
separator (-).
$newstring[0] holds value of: My
$newstring[1] holds value of: name
$newstring[2] holds value of: is
$newstring[3] holds value of: John
Example 2:
$fullstring="Her name is Mary Jenkins";
$newstring=explode(" ",$fullstring);
This results in an array of 5 elements, each part a substring and each part separated by a single
whitespace.
$newstring[0] holds value of: Her
$newstring[1] holds value of: name
$newstring[2] holds value of: is
$newstring[3] holds value of: Mary
$newstring[4] holds value of: Jenkins

HOW TO USE THE empty() FUNCTION IN PHP


The empty() function is used to check whether a defined variable has a value which is an empty
string, empty array, zero or NULL. Returns true if it is and false if it is not empty or undefined.

Please note the the empty() function only works on variables and it's use on anything else will
produce errors.
Example Usage:
<?
$username='';
if(empty($username))
{
echo "This variable is empty";
}
else
{
echo "This variable is not empty";
}
?>
In the above example, the output will be: This variable is empty. This is because $username has
an empty string '' as value.

PHP Sessions

A PHP session variable is used to store information about, or change settings for a user session.
Session variables hold information about one single user, and are available to all pages in one
application.

PHP Session Variables


When you are working with an application, you open it, do some changes and then you close it.
This is much like a Session. The computer knows who you are. It knows when you start the
application and when you end. But on the internet there is one problem: the web server does not
know who you are and what you do because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store user information on the server for
later use (i.e. username, shopping items, etc). However, session information is temporary and
will be deleted after the user has left the website. If you need a permanent storage you may
want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID.
The UID is either stored in a cookie or is propagated in the URL.

Starting a PHP Session

Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the <html> tag:
<?php session_start(); ?>
<html>
<body>
</body>
</html>

The code above will register the user's session with the server, allow you to start saving user
information, and assign a UID for that user's session.

Storing a Session Variable


The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>

Output:
Pageviews=1

In the example below, we create a simple page-views counter. The isset() function checks if the
"views" variable has already been set. If "views" has been set, we can increment our counter. If
"views" doesn't exist, we create a "views" variable, and set it to 1:
<?php
session_start();
if(isset($_SESSION['views']))

$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>

Destroying a Session
If you wish to delete some session data, you can use the unset() or the session_destroy()
function.
The unset() function is used to free the specified session variable:
<?php
unset($_SESSION['views']);
?>

You can also completely destroy the session by calling the session_destroy() function:
<?php
session_destroy();
?>

Note: session_destroy() will reset your session and you will lose all your stored session data.

MySQL PHP Functions


PHP MySQL Introduction
The MySQL functions allows you to access MySQL database servers.

Runtime Configuration
The behavior of the MySQL functions is affected by settings in the php.ini file.
MySQL configuration options:
Name

Default

Description

Changeable

mysql.allow_persist "1"
ent

Whether or not to allow persistent


connections

PHP_INI_SYSTEM

mysql.max_persiste "-1"
nt

The maximum number of persistent


connections per process

PHP_INI_SYSTEM

mysql.max_links

"-1"

The maximum number of connections


per process (persistent connections
included)

PHP_INI_SYSTEM

mysql.trace_mode

"0"

Trace mode. When set to "1", warnings

PHP_INI_ALL

and SQL-errors will be displayed.


Available since PHP 4.3
mysql.default_port

NULL

The default TCP port number to use

PHP_INI_ALL

mysql.default_socke NULL
t

The default socket name to use.


Available since PHP 4.0.1

PHP_INI_ALL

mysql.default_host

NULL

The default server host to use (doesn't


apply in SQL safe mode)

PHP_INI_ALL

mysql.default_user

NULL

The default user name to use (doesn't


apply in SQL safe mode)

PHP_INI_ALL

mysql.default_pass NULL
word

The default password to use (doesn't


apply in SQL safe mode)

PHP_INI_ALL

mysql.connect_time "60"
out

Connection timeout in seconds

PHP_INI_ALL

Resource Types
There are two resource types used in the MySQL extension. The first one is the link_identifier for
a database connection, the second is a resource which holds the result of a query.
Note: Most MySQL functions accept link_identifier as the last optional parameter. If it is not
provided, the last opened connection is used

PHP MySQL Functions


PHP: indicates the earliest version of PHP that supports the function.
Function

Description

PHP

mysql_affected_rows()

Returns the number of affected rows in the previous


MySQL operation

mysql_change_user()

Deprecated. Changes the user of the current MySQL


connection

mysql_client_encoding()

Returns the name of the character set for the current


connection

mysql_close()

Closes a non-persistent MySQL connection

mysql_connect()

Opens a non-persistent MySQL connection

mysql_create_db()

Deprecated. Creates a new MySQL database. Use


mysql_query() instead

mysql_data_seek()

Moves the record pointer

mysql_db_name()

Returns a database name from a call to mysql_list_dbs()

mysql_db_query()

Deprecated. Sends a MySQL query. Use mysql_select_db() 3


and mysql_query() instead

mysql_drop_db()

Deprecated. Deletes a MySQL database. Use


mysql_query() instead

mysql_errno()

Returns the error number of the last MySQL operation

mysql_error()

Returns the error description of the last MySQL operation

mysql_escape_string()

Deprecated. Escapes a string for use in a mysql_query. Use 4


mysql_real_escape_string() instead

mysql_fetch_array()

Returns a row from a recordset as an associative array


and/or a numeric array

mysql_fetch_assoc()

Returns a row from a recordset as an associative array

mysql_fetch_field()

Returns column info from a recordset as an object

mysql_fetch_lengths()

Returns the length of the contents of each field in a result 3


row

mysql_fetch_object()

Returns a row from a recordset as an object

mysql_fetch_row()

Returns a row from a recordset as a numeric array

mysql_field_flags()

Returns the flags associated with a field in a recordset

mysql_field_len()

Returns the maximum length of a field in a recordset

mysql_field_name()

Returns the name of a field in a recordset

mysql_field_seek()

Moves the result pointer to a specified field

mysql_field_table()

Returns the name of the table the specified field is in

mysql_field_type()

Returns the type of a field in a recordset

mysql_free_result()

Free result memory

mysql_get_client_info()

Returns MySQL client info

mysql_get_host_info()

Returns MySQL host info

mysql_get_proto_info()

Returns MySQL protocol info

mysql_get_server_info()

Returns MySQL server info

mysql_info()

Returns information about the last query

mysql_insert_id()

Returns the AUTO_INCREMENT ID generated from the


previous INSERT operation

mysql_list_dbs()

Lists available databases on a MySQL server

mysql_list_fields()

Deprecated. Lists MySQL table fields. Use mysql_query()


instead

mysql_list_processes()

Lists MySQL processes

mysql_list_tables()

Deprecated. Lists tables in a MySQL database. Use


mysql_query() instead

mysql_num_fields()

Returns the number of fields in a recordset

mysql_num_rows()

Returns the number of rows in a recordset

mysql_pconnect()

Opens a persistent MySQL connection

mysql_ping()

Pings a server connection or reconnects if there is no


connection

mysql_query()

Executes a query on a MySQL database

mysql_real_escape_string()

Escapes a string for use in SQL statements

mysql_result()

Returns the value of a field in a recordset

mysql_select_db()

Sets the active MySQL database

mysql_stat()

Returns the current system status of the MySQL server

mysql_tablename()

Deprecated. Returns the table name of field. Use


mysql_query() instead

mysql_thread_id()

Returns the current thread ID

PHP : is_array() function


Description

The is_array() function is used to find whether a variable is an array or not.


Syntax
is_array (var_name)
Parameter
Name
var_name

Description
The variable being checked

Required /
Optional
Required

Type
Mixed*

*Mixed : Mixed indicates that a parameter may accept multiple (but not necessarily all) types.
Return value
TRUE if var is an array, FALSE otherwise.
Value Type : Boolean.
Example of php is_array() function
<?php
$var_name=array('A','B','C');
if (is_array($var_name))
echo 'This is an array....';
else
echo 'This is not an array....';
?>
Output of the example
This is an array....

Creating runtime functions


Creating runtime functions is a very good way of making the script more dynamic:
$function_name=create_function('$one, $two','return $one+$two;');
echo $function_name."\n\n";
echo $function_name("1.5", "2");
create_function creates a function with parameters $one and $two, with a code to evaluate
return... When create_function is executed, it stores the function's info in the memory and
returns the function's name. This means that you cannot customise the name of the function
although that would be preferred by most developers.

PHP echo() Function

Definition and Usage


The echo() function outputs one or more strings.
Syntax
echo(strings)
Parameter

Description

Strings

Required. One or more strings to be sent to the output

Tips and Notes


Note: The echo() function is not actually a function, so you are not required to use parentheses
with it. However, if you want to pass more than one parameter to echo(), using parentheses will
generate a parse error.
Tip: The echo() function is slightly faster than print().
Tip: The echo() function has the following shortcut syntax. See example 5.
Example 1
<?php
$str = "Who's Kai Jim?";
echo $str;
echo "<br />";
echo $str."<br />I don't know!";
?>
The output of the code above will be:
Who's Kai Jim?
Who's Kai Jim?
I don't know!
Example 2
<?php
echo "This text
spans multiple
lines.";
?>
The output of the code above will be:
This text spans multiple lines.
Example 3
<?php
echo 'This ','string ','was ','made ','with multiple parameters';

?>
The output of the code above will be:
This string was made with multiple parameters
Example 4
Difference of single and double quotes. Single quotes will print the variable name, not the value:
<?php
$color = "red";
echo "Roses are $color";
echo "<br />";
echo 'Roses are $color';
?>
The output of the code above will be:
Roses are red
Roses are $color
Example 5
Shortcut syntax:
<html>
<body>
<?php
$color = "red";
?>
<p>Roses are <?=$color?></p>
</body>
</html>

PHP - Echo
As you saw in the previous lesson, the PHP command echo is a means of outputting text to the
web browser. Throughout your PHP career you will be using the echo command more than any
other. So let's give it a solid perusal!

Outputting a String
To output a string, like we have done in previous lessons, use PHP echo. You can place either a
string variable or you can use quotes, like we do below, to create a string that the echo function
will output.

PHP Code:
<?php
$myString = "Hello!";
echo $myString;
echo "<h5>I love using PHP!</h5>";
?>
Display:
Hello!
I love using PHP!
In the above example we output "Hello!" without a hitch. The text we are outputting is being sent
to the user in the form of a web page, so it is important that we use proper HTML syntax!
In our second echo statement we use echo to write a valid Header 5 HTML statement. To do this
we simply put the <h5> at the beginning of the string and closed it at the end of the string. Just
because you're using PHP to make web pages does not mean you can forget about HTML sy ntax!

Careful When Echoing Quotes!


It is pretty cool that you can output HTML with PHP. However, you must be careful when
using HTML code or any other string that includes quotes! Echo uses quotes to define the
beginning and end of the string, so you must use one of the following tactics if your string
contains quotations:

Don't use quotes inside your string


Escape your quotes that are within the string with a backslash. To escape a quote just
place a backslash directly before the quotation mark, i.e. \"

Use single quotes (apostrophes) for quotes inside your string.

See our example below for the right and wrong use of echo:
PHP Code:
<?php
// This won't work because of the quotes around specialH5!
echo "<h5 class="specialH5">I love using PHP!</h5>";
// OK because we escaped the quotes!
echo "<h5 class=\"specialH5\">I love using PHP!</h5>";
// OK because we used an apostrophe '
echo "<h5 class='specialH5'>I love using PHP!</h5>";
?>
If you want to output a string that includes quotations, either use an apostrophe ( ' ) or escape
the quotations by placing a backslash in front of it ( \" ). The backslash will tell PHP that you want
the quotation to be used within the string and NOT to be used to end echo's string.

Echoing Variables

Echoing variables is very easy. The PHP developers put in some extra work to make the common
task of echoing all variables nearly foolproof! No quotations are required, even if the variable
does not hold a string. Below is the correct format for echoing a variable.
PHP Code:
<?php
$my_string = "Hello Bob. My name is: ";
$my_number = 4;
$my_letter = a;
echo $my_string;
echo $my_number;
echo $my_letter;
?>
Display:
Hello Bob. My name is: 4a

Echoing Variables and Text Strings


You can also place variables inside of double-quoted strings (e.g. "string here and a $variable").
By putting a variable inside the quotes (" ") you are telling PHP that you want it to grab the string
value of that variable and use it in the string. The example below shows an example of this cool
feature.
PHP Code:
<?php
$my_string = "Hello Bob. My name is: ";
echo "$my_string Bobettta <br />";
echo "Hi, I'm Bob. Who are you? $my_string <br />";
echo "Hi, I'm Bob. Who are you? $my_string Bobetta";
?>
Display:
Hello Bob. My name is: Bobetta
Hi, I'm Bob. Who are you? Hello Bob. My name is:
Hi, I'm Bob. Who are you? Hello Bob. My name is: Bobetta
By placing variables inside a string you can save yourself some time and make your code easier
to read, though it does take some getting used to. Remember to use double-quotes, singlequotes will not grab the value of the string. Single-quotes will just output the variable name to
the string, like )$my_string), rather than (Hello Bob. My name is: ).

PHP Echo - Not a Function


Echo is not a function, rather it is a language construct. When you use functions in PHP, they
have a very particular form, which we will be going over later. For now, just know that echo is a
special tool that you'll come to know and love!

Tips and Notes

Note: The echo() function is not actually a function, so you are not required to use parentheses
with it. However, if you want to pass more than one parameter to echo(), using parentheses will
generate a parse error.
Tip: The echo() function is slightly faster than print().
Tip: The echo() function has the following shortcut syntax. See example 5.
Example 1
<?php
$str = "Who's Kai Jim?";
echo $str;
echo "<br />";
echo $str."<br />I don't know!";
?>

The output of the code above will be:


Who's Kai Jim?
Who's Kai Jim?
I don't know!
Example 2
<?php
echo "This text
spans multiple
lines.";
?>
The output of the code above will be:
This text spans multiple lines.
Example 3
<?php
echo 'This ','string ','was ','made ','with multiple parameters';
?>

The output of the code above will be:


This string was made with multiple parameters
Example 4

Difference of single and double quotes. Single quotes will print the variable name, not the value:
<?php
$color = "red";
echo "Roses are $color";
echo "<br />";
echo 'Roses are $color';
?>

The output of the code above will be:


Roses are red
Roses are $color
Example 5
Shortcut syntax:
<html>
<body>
<?php
$color = "red";
?>
<p>Roses are <?=$color?></p>
</body>
</html>

HOW TO OUTPUT TO SCREEN WITH PHP USING ECHO


PHP has a built-in way to display output to screen. You would use an ECHO statement to output
html to screen.
See this simple example.
<?
echo "John Smith";
?>
When you run this, it will output John Smith to your screen. PHP can also output HTML code as in
the following example:
<?

echo "<b>John Smith</b>";


?>
When you run this, it will output John Smith (bolded) to your screen. Look at the page source for
this. It will show: <b>John Smith</b>
What happens when you echo with PHP is that PHP processes this echo statement and sends the
output to the web server which in turn sends this output to your browser. Also note that you web
browser can only read html (it reads text but in html format) and not PHP. It is the PHP processor
on the web server that reads PHP statements and then outputs it as HTML to your browser which
then displays it for you to read off your screen.
Points to remember when using the echo statement:
1. The echo statement starts with the word echo.
2. Strings must be surrounded with single or double quotes (a string is a combination of
characters, text or numbers).
3. Numbers on their own do not need to be enclosed with quotes.
4. Echo statement must be terminated at end line with a semi-colon.
Further examples:
Echo
statement

Outputs

echo "John
Smith";

John Smith

echo 'John
Smith';

John Smith

echo 699;

699

echo "John
Smith"

error, no terminating semicolon

echo John
Smith;

error, no enclosed quotes

PHP mysql_num_rows() Function


Definition and Usage
The mysql_num_rows() function returns the number of rows in a recordset.
This function returns FALSE on failure.
Syntax
mysql_num_rows(data)

Parameter

Description

data

Required. Specifies which data pointer to use. The data pointer is the result
from the mysql_query() function

Example
<?php
$con = mysql_connect("localhost", "peter", "abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("test_db",$con);
$sql = "SELECT * FROM person";
$result = mysql_query($sql,$con);
echo mysql_num_rows($result);
mysql_close($con);
?>

The output of the code above could be:


4

PHP mysql_fetch_row() Function


Definition and Usage
The mysql_fetch_row() function returns a row from a recordset as a numeric array.
This function gets a row from the mysql_query() function and returns an array on success, or
FALSE on failure or when there are no more rows.
Syntax
mysql_fetch_row(data)

Parameter

Description

data

Required. Specifies which data pointer to use. The data pointer is the result

from the mysql_query() function

Tips and Notes


Note: After the data is retrieved, this function moves to the next row in the recordset. Each
subsequent call to mysql_fetch_assoc() returns the next row in the recordset.
Example
<?php
$con = mysql_connect("localhost", "peter", "abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("test_db",$con);
$sql = "SELECT * from Person WHERE Lastname='Refsnes'";
$result = mysql_query($sql,$con);
print_r(mysql_fetch_row($result));
mysql_close($con);
?>

The output of the code above could be:


Array
(
[0] =>
[1] =>
[2] =>
[3] =>
)

Refsnes
Kai Jim
Taugata 2
22

mysql_fetch_row
mysql_fetch_row Get a result row as an enumerated array
array mysql_fetch_row ( resource $result )
Returns a numerical array that corresponds to the fetched row and moves the internal data
pointer ahead.
The result resource that is being evaluated. This result comes from a call to mysql_query().

Returns an numerical array of strings that corresponds to the fetched row, or FALSE if there are
no more rows.
mysql_fetch_row() fetches one row of data from the result associated with the specified result
identifier. The row is returned as an array. Each result column is stored in an array offset, starting
at offset 0.

Example #1 Fetching one row with mysql_fetch_row()


<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
Note: This function sets NULL fields to the PHP NULL value.

PHP mysql_fetch_array() Function


Definition and Usage
The mysql_fetch_array() function returns a row from a recordset as an associative array and/or a
numeric array.
This function gets a row from the mysql_query() function and returns an array on success, or
FALSE on failure or when there are no more rows.
Syntax
mysql_fetch_array(data,array_type)

Parameter

Description

data

Required. Specifies which data pointer to use. The data pointer is the result
from the mysql_query() function

array_type

Optional. Specifies what kind of array to return.


Possible values:

MYSQL_ASSOC - Associative array


MYSQL_NUM - Numeric array

MYSQL_BOTH - Default. Both associative and numeric array

Tips and Notes


Note: After the data is retrieved, this function moves to the next row in the recordset. Each
subsequent call to mysql_fetch_array() returns the next row in the recordset.
Tip: Field names returned by this function are case-sensitive.
Example
<?php
$con = mysql_connect("localhost", "peter", "abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("test_db",$con);
$sql = "SELECT * from Person WHERE Lastname='Refsnes'";
$result = mysql_query($sql,$con);
print_r(mysql_fetch_array($result));
mysql_close($con);
?>

The output of the code above could be:


Array
(
[0] => Refsnes
[LastName] => Refsnes
[1] => Kai Jim
[FirstName] => Kai Jim
[2] => Taugata 2
[Address] => Taugata 2
[3] => 22
[Age] => 22
)

mysql_fetch_assoc
mysql_fetch_assoc Fetch a result row as an associative array
Report a bug

Description
array mysql_fetch_assoc ( resource $result )
Returns an associative array that corresponds to the fetched row and moves the internal data
pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with
MYSQL_ASSOC for the optional second parameter. It only returns an associative array.

Parameters
result

The result resource that is being evaluated. This result comes from a call to mysql_query().

Return Values
Returns an associative array of strings that corresponds to the fetched row, or FALSE if there are
no more rows.
If two or more columns of the result have the same field names, the last column will take
precedence. To access the other column(s) of the same name, you either need to access the
result with numeric indices by using mysql_fetch_row() or add alias names. See the example at
the mysql_fetch_array() description about aliases.

Examples
Example #1 An expanded mysql_fetch_assoc() example
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) {

echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
//
then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
?>
Note: Performance
An important thing to note is that using mysql_fetch_assoc() is not significantly slower
than using mysql_fetch_row(), while it provides a significant added value.
Note: Field names returned by this function are case-sensitive.
Note: This function sets NULL fields to the PHP NULL value.

PHP mysql_fetch_assoc() Function


Definition and Usage
The mysql_fetch_assoc() function returns a row from a recordset as an associative array.
This function gets a row from the mysql_query() function and returns an array on success, or
FALSE on failure or when there are no more rows.
Syntax
mysql_fetch_assoc(data)

Parameter

Description

data

Required. Specifies which data pointer to use. The data pointer is the result

from the mysql_query() function

Tips and Notes


Note: After the data is retrieved, this function moves to the next row in the recordset. Each
subsequent call to mysql_fetch_assoc() returns the next row in the recordset.
Tip: Field names returned by this function are case-sensitive.
Example
<?php
$con = mysql_connect("localhost", "peter", "abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("test_db",$con);
$sql = "SELECT * from Person WHERE Lastname='Refsnes'";
$result = mysql_query($sql,$con);
print_r(mysql_fetch_assoc($result));
mysql_close($con);
?>

The output of the code above could be:


Array
(
[LastName] => Refsnes
[FirstName] => Kai Jim
[Address] => Taugata 2
[Age] => 22

mysql_fetch_object
mysql_fetch_object Fetch a result row as an object
Description
object mysql_fetch_object ( resource $result [, string $class_name [, array $params ]] )

Returns an object with properties that correspond to the fetched row and moves the internal data
pointer ahead.
Parameters
result

The result resource that is being evaluated. This result comes from a call to mysql_query().
class_name

The name of the class to instantiate, set the properties of and return. If not specified, a stdClass
object is returned.
params

An optional array of parameters to pass to the constructor for class_name objects.


Return Values
Returns an object with string properties that correspond to the fetched row, or FALSE if there are
no more rows.

Example #1 mysql_fetch_object() example


<?php
mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");
$result = mysql_query("select * from mytable");
while ($row = mysql_fetch_object($result)) {
echo $row->user_id;
echo $row->fullname;
}
mysql_free_result($result);
?>

Example #2 mysql_fetch_object() example


<?php
class foo {
public $name;
}
mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");
$result = mysql_query("select name from mytable limit 1");
$obj = mysql_fetch_object($result, 'foo');
var_dump($obj);
?>
Report a bug

Notes
Note: Performance
Speed-wise, the function is identical to mysql_fetch_array(), and almost as quick as
mysql_fetch_row() (the difference is insignificant).
Note:
mysql_fetch_object() is similar to mysql_fetch_array(), with one difference - an
object is returned, instead of an array. Indirectly, that means that you can only
access the data by the field names, and not by their offsets (numbers are illegal
property names).
Note: Field names returned by this function are case-sensitive.
Note: This function sets NULL fields to the PHP NULL value.

PHP mysql_fetch_object() Function

Definition and Usage


The mysql_fetch_object() function returns a row from a recordset as an object.
This function gets a row from the mysql_query() function and returns an object on success, or
FALSE on failure or when there are no more rows.
Syntax
mysql_fetch_object(data)

Parameter

Description

data

Required. Specifies which data pointer to use. The data pointer is the result
from the mysql_query() function

Tips and Notes


Note: Each subsequent call to mysql_fetch_object() returns the next row in the recordset.
Example
<?php
$con = mysql_connect("localhost", "peter", "abc123");
if (!$con)

{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("test_db",$con);
$sql = "SELECT * from Person";
$result = mysql_query($sql,$con);
while ($row = mysql_fetch_object($result))
{
echo $row->FirstName . "<br />";
}
mysql_close($con);
?>

The output of the code above could be:


Kai Jim
Stle
Hege

PHP die() Function


Definition and Usage
The die() function prints a message and exits the current script.
This function is an alias of the exit() function.
Syntax
die(message)

Parameter

Description

message

Required. Specifies the message or status number to write before exiting the
script. The status number will not be written to the output.

Example
<?php
$site = "http://www.w3schools.com/";
fopen($site,"r")
or die("Unable to connect to $site");

?>

isset
Determine if a variable is set and is not NULL
bool isset ( mixed $var [, mixed $... ] )
Determine if a variable is set and is not NULL.
If a variable has been unset with unset(), it will no longer be set. isset() will return FALSE if
testing a variable that has been set to NULL. Also note that a NULL byte ("\0") is not equivalent
to the PHP NULL constant.
If multiple parameters are supplied then isset() will return TRUE only if all of the parameters are
set. Evaluation goes from left to right and stops as soon as an unset variable is encountered.
Returns TRUE if var exists and has value other than NULL, FALSE otherwise.

Example #1 isset() Examples


<?php
$var = '';
// This will evaluate to TRUE so the text will be printed.
if (isset($var)) {
echo "This var is set so I will print.";
}
// In the next examples we'll use var_dump to output
// the return value of isset().
$a = "test";
$b = "anothertest";
var_dump(isset($a));
// TRUE
var_dump(isset($a, $b)); // TRUE
unset ($a);
var_dump(isset($a));
// FALSE
var_dump(isset($a, $b)); // FALSE
$foo = NULL;
var_dump(isset($foo)); // FALSE
?>

This also work for elements in arrays:


<?php
$a = array ('test' => 1, 'hello' => NULL, 'pie' => array('a' => 'apple'));
var_dump(isset($a['test']));
var_dump(isset($a['foo']));
var_dump(isset($a['hello']));

// TRUE
// FALSE
// FALSE

// The key 'hello' equals NULL so is considered unset


// If you want to check for NULL key values then try:
var_dump(array_key_exists('hello', $a)); // TRUE
// Checking deeper array values
var_dump(isset($a['pie']['a']));
// TRUE
var_dump(isset($a['pie']['b']));
// FALSE
var_dump(isset($a['cake']['a']['b'])); // FALSE
?>
Warning
isset() only works with variables as passing anything else will result in a parse error. For
checking if constants are set use the defined() function.
Note: Because this is a language construct and not a function, it cannot be called using variable
functions
Note:
When using isset() on inaccessible object properties, the __isset overloading method will be
called, if declared.

PHP : is_array() function


Description
The is_array() function is used to find whether a variable is an array or not.
Syntax
is_array (var_name)
Parameter
Name

Description

Required /

Type

Optional
var_name

The variable being checked

Required

Mixed*

*Mixed : Mixed indicates that a parameter may accept multiple (but not necessarily all) types.
Return value
TRUE if var is an array, FALSE otherwise.
Value Type : Boolean.
Example of php is_array() function
<?php
$var_name=array('A','B','C');
if (is_array($var_name))
echo 'This is an array....';
else
echo 'This is not an array....';
?>
Output of the example
This is an array....

PHP move_uploaded_file() Function


Definition and Usage
The move_uploaded_file() function moves an uploaded file to a new location.
This function returns TRUE on success, or FALSE on failure.
Syntax
move_uploaded_file(file,newloc)

Parameter

Description

file

Required. Specifies the file to be moved

newloc

Required. Specifies the new location for the file

Tips and Notes


Note: This function only works on files uploaded via HTTP POST.
Note: If the destination file already exists, it will be overwritten.

move_uploaded_file
move_uploaded_file Moves an uploaded file to a new location

Description
bool move_uploaded_file ( string $filename , string $destination )
This function checks to ensure that the file designated by filename is a valid upload file (meaning
that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved
to the filename given by destination.
This sort of check is especially important if there is any chance that anything done with uploaded
files could reveal their contents to the user, or even to other users on the same system.

Parameters
filename

The filename of the uploaded file.


destination

The destination of the moved file.

Return Values

Returns TRUE on success.


If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will
return FALSE.
If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and
move_uploaded_file() will return FALSE. Additionally, a warning will be issued.

Examples
Example #1 Uploading multiple files
<?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>

Note:
move_uploaded_file() is both safe mode and open_basedir aware. However, restrictions are
placed only on the destination path as to allow the moving of uploaded files in which filename
may conflict with such restrictions. move_uploaded_file() ensures the safety of this operation
by allowing only those files uploaded through PHP to be moved.
Warning
If the destination file already exists, it will be overwritten.

mssql_next_result
mssql_next_result Move the internal result pointer to the next result
Description
bool mssql_next_result ( resource $result_id )
When sending more than one SQL statement to the server or executing a stored procedure with
multiple results, it will cause the server to return multiple result sets. This function will test for
additional results available form the server. If an additional result set exists it will free the
existing result set and prepare to fetch the rows from the new result set.
Parameters
result_id

The result resource that is being evaluated. This result comes from a call to mssql_query()
Return Values
Returns TRUE if an additional result set was available or FALSE otherwise.
Examples

Example #1 mssql_next_result() example


<?php
// Connect to MSSQL and select the database
$link = mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);
// Send a query to MSSQL
$sql = 'SELECT [name], [age] FROM [php].[dbo].[persons]';
$query = mssql_query($sql, $link);
// Iterate through returned records
do {
while ($row = mssql_fetch_row($query)) {
// Handle record ...

}
} while (mssql_next_result($query));
// Clean up
mssql_free_result($query);
mssql_close($link);
?>

CONCATENATION: HOW TO JOIN STRINGS IN PHP


It is possible to join strings in PHP and this process is referred to as Concatenation.
Example:
$string1="John";
$string2="Smith";
$joinedString=$string1.$string2;
echo $joinedString;
Notice that we used a . to join the strings. The above will output JohnSmith. Notice that the words
JohnSmith have no space in them. To give it a space, do as follows:
$string1="John";
$string2="Smith";
$joinedString=$string1." ".$string2;
echo $joinedString;
The above will now output John Smith.
You can also add to an existing string using .= as follows:
$string ="John";
$string .="Smith";
echo $string;
This will output JohnSmith. To add a space betwen John and Smith,

$string ="John";
$string .=" ";
$string .="Smith";
echo $string;
This will output John Smith. Another way to add a space,
$string ="John";
$string .=" Smith";
echo $string;
This will output John Smith. Note the space before Smith in the se

PHP Sending E-mails


PHP allows you to send e-mails directly from a script.

The PHP mail() Function


The PHP mail() function is used to send emails from inside a script.
Syntax
mail(to,subject,message,headers,parameters)

Parameter

Description

to

Required. Specifies the receiver / receivers of the email

subject

Required. Specifies the subject of the email. Note: This parameter cannot
contain any newline characters

message

Required. Defines the message to be sent. Each line should be separated with
a LF (\n). Lines should not exceed 70 characters

headers

Optional. Specifies additional headers, like From, Cc, and Bcc. The additional
headers should be separated with a CRLF (\r\n)

parameters

Optional. Specifies an additional parameter to the sendmail program

Note: For the mail functions to be available, PHP requires an installed and working email system.
The program to be used is defined by the configuration settings in the php.ini file. Read more in
our PHP Mail reference.

PHP Simple E-Mail


The simplest way to send an email with PHP is to send a text email.
In the example below we first declare the variables ($to, $subject, $message, $from, $headers),
then we use the variables in the mail() function to send an e-mail:
<?php
$to = "someone@example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse@example.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>

PHP Mail Form


With PHP, you can create a feedback-form on your website. The example below sends a text
message to a specified e-mail address:
<html>
<body>
<?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
{
//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail("someone@example.com", "$subject",
$message, "From:" . $email);
echo "Thank you for using our mail form";
}
else
//if "email" is not filled out, display the form
{
echo "<form method='post' action='mailform.php'>
Email: <input name='email' type='text' /><br />
Subject: <input name='subject' type='text' /><br />

Message:<br />
<textarea name='message' rows='15' cols='40'>
</textarea><br />
<input type='submit' />
</form>";
}
?>
</body>
</html>

This is how the example above works:

First, check if the email input field is filled out


If it is not set (like when the page is first visited); output the HTML form

If it is set (after the form is filled out); send the email from the form

When submit is pressed after the form is filled out, the page reloads, sees that the email
input is set, and sends the email

Note: This is the simplest way to send e-mail, but it is not secure. In the next chapter of this
tutorial you can read more about vulnerabilities in e-mail scripts, and how to validate user input
to make it more secure.

PHP File Upload

With PHP, it is possible to upload files to the server.

Create an Upload-File Form


To allow users to upload files from a form can be very useful.
Look at the following HTML form for uploading files:
<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>
Notice the following about the HTML form above:

The enctype attribute of the <form> tag specifies which content-type to use when
submitting the form. "multipart/form-data" is used when a form requires binary data, like
the contents of a file, to be uploaded
The type="file" attribute of the <input> tag specifies that the input should be processed
as a file. For example, when viewed in a browser, there will be a browse-button next to the
input field

Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform
file uploads.

Create The Upload Script


The "upload_file.php" file contains the code for uploading a file:
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
?>
By using the global PHP $_FILES array you can upload files from a client computer to the remote
server.
The first parameter is the form's input name and the second index can be either "name", "type",
"size", "tmp_name" or "error". Like this:

$_FILES["file"]["name"] - the name of the uploaded file


$_FILES["file"]["type"] - the type of the uploaded file

$_FILES["file"]["size"] - the size in bytes of the uploaded file

$_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the
server

$_FILES["file"]["error"] - the error code resulting from the file upload

This is a very simple way of uploading files. For security reasons, you should add restrictions on
what the user is allowed to upload.

Restrictions on Upload
In this script we add some restrictions to the file upload. The user may only upload .gif or .jpeg
files and the file size must be under 20 kb:
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
}
else
{
echo "Invalid file";
}
?>
Note: For IE to recognize jpg files the type must be pjpeg, for FireFox it must be jpeg.

Saving the Uploaded File


The examples above create a temporary copy of the uploaded files in the PHP temp folder on the
server.
The temporary copied files disappears when the script ends. To store the uploaded file we need
to copy it to a different location:
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}

else
{
echo
echo
echo
echo

"Upload: " . $_FILES["file"]["name"] . "<br />";


"Type: " . $_FILES["file"]["type"] . "<br />";
"Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
"Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
The script above checks if the file already exists, if it does not, it copies the file to the specified
folder.
Note: This example saves the file to a new folder called "upload"

Uploading Files To MySQL Database


Using PHP to upload files into MySQL database sometimes needed by some web application. For
instance for storing pdf documents or images to make som kind of online briefcase (like Yahoo
briefcase).
For the first step, let's make the table for the upload files. The table will consist of.
1. id : Unique id for each file
2. name : File name
3. type : File content type
4. size : File size
5. content : The file itself

For column content we'll use BLOB data type. BLOB is a binary large object that can

hold a variable amount of data. MySQL have four BLOB data types, they are :

TINYBLOB
BLOB

MEDIUMBLOB

LONGBLOB

Since BLOB is limited to store up to 64 kilobytes of data we will use MEDIUMBLOB so we


can store larger files ( up to 16 megabytes ).
CREATE TABLE upload (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
type VARCHAR(30) NOT NULL,
size INT NOT NULL,
content MEDIUMBLOB NOT NULL,
PRIMARY KEY(id)
);
Uploading a file to MySQL is a two step process. First you need to upload the file to the
server then read the file and insert it to MySQL.
For uploading a file we need a form for the user to enter the file name or browse their
computer and select a file. The input type="file" is used for that purpose.

Example : upload.php
Source code : upload.phps
<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload"
value=" Upload "></td>
</tr>
</table>
</form>
An upload form must have encytype="multipart/form-data" otherwise it won't work at
all. Of course the form method also need to be set to method="post". Also remember
to put a hidden input MAX_FILE_SIZE before the file input. It's to restrict the size of
files.
After the form is submitted the we need to read the autoglobal $_FILES. In the example
above the input name for the file is userfile so the content of $_FILES are like this :
$_FILES['userfile']['name']

The original name of the file on the client machine.


$_FILES['userfile']['type']
The mime type of the file, if the browser provided this information. An example would
be "image/gif".
$_FILES['userfile']['size']
The size, in bytes, of the uploaded file.
$_FILES['userfile']['tmp_name']
The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES['userfile']['error']
The error code associated with this file upload. ['error'] was added in PHP 4.2.0

Example : upload.php

<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp
= fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
include 'library/config.php';
include 'library/opendb.php';
$query = "INSERT INTO upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
include 'library/closedb.php';
echo "<br>File $fileName uploaded<br>";
}
?>

Before you do anything with the uploaded file. You should not assume that the file
was uploaded successfully to the server. Always check to see if the file was successfully
uploaded by looking at the file size. If it's larger than zero byte then we can assume
that the file is uploaded successfully.
PHP saves the uploaded file with a temporary name and save the name in
$_FILES['userfile']['tmp_name']. Our next job is to read the content of this file and insert
the content to database. Always make sure that you use addslashes() to escape the
content. Using addslashes() to the file name is also recommended because you never
know what the file name would be.
That's it now you can upload your files to MySQL. Now it's time to write the script to
download those files.

Downloading Files From MySQL Database


When we upload a file to database we also save the file type and length. These were
not needed for uploading the files but is needed for downloading the files from the
database.
The download page list the file names stored in database. The names are printed as a
url. The url would look like download.php?id=3. To see a working example click here. I
saved several images in my database, you can try downloading them.
Example :
<html>
<head>
<title>Download File From MySQL</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<?php
include 'library/config.php';
include 'library/opendb.php';
$query = "SELECT id, name FROM upload";
$result = mysql_query($query) or die('Error, query failed');
if(mysql_num_rows($result) == 0)
{
echo "Database is empty <br>";
}
else
{
while(list($id, $name) = mysql_fetch_array($result))
{
?>
<a href="download.php?id=<?php=$id;?>"><?php=$name;?></a> <br>
<?php
}

}
include 'library/closedb.php';
?>
</body>
</html>

When you click the download link, the $_GET['id'] will be set. We can use this id to identify which
files to get from the database. Below is the code for downloading files from MySQL Database.
Example :
<?php
if(isset($_GET['id']))
{
// if id is set then get the file with the id from database
include 'library/config.php';
include 'library/opendb.php';
$id = $_GET['id'];
$query = "SELECT name, type, size, content " .
"FROM upload WHERE id = '$id'";
$result = mysql_query($query) or die('Error, query failed');
list($name, $type, $size, $content) =
mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $content;
include 'library/closedb.php';
exit;
}
?>
Before sending the file content using echo first we need to set several headers. They are :
1. header("Content-length: $size")
This header tells the browser how large the file is. Some browser need it to be able to
download the file properly. Anyway it's a good manner telling how big the file is. That way
anyone who download the file can predict how long the download will take.
2. header("Content-type: $type")
This header tells the browser what kind of file it tries to download.
3. header("Content-Disposition: attachment; filename=$name");
Tells the browser to save this downloaded file under the specified name. If you don't send
this header the browser will try to save the file using the script's name (download.php).
After sending the file the script stops executing by calling exit.

NOTE :
When sending headers the most common error message you will see is something like this :
Warning: Cannot modify header information - headers already sent by (output started at
C:\Webroot\library\config.php:7) in C:\Webroot\download.php on line 13
This error happens because some data was already sent before we send the header. As for the
error message above it happens because i "accidentally" add one space right after the PHP
closing tag ( ?> ) in config.php file. So if you see this error message when you're sending a
header just make sure you don't have any data sent before calling header(). Check the file
mentioned in the error message and go to the line number specified
How to set the images to be W= 288 pixels X H= 216 pixels ?
Thanks a lot.
###########################################
<?php
$dbname="your database";
$host="localhost";
$user="db user";
$pass="db password";
$link = mysql_connect($hostname, $user, $pass);
mysql_select_db($dbname, $link);
?>
<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value="
Upload "></td>
</tr>
</table>
</form>
<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp

= fopen($tmpName, 'r');

$content = fread($fp, filesize($tmpName));

$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
echo "<br>File $fileName uploaded<br>";
}
?>
Need Help Downloading Files from MySQL Database
PHP Syntax
1.
2. <?php session_start();
3. $DBconnection = mysqli_connect("localhost", "<db_name>",
"<db_password>","<table_name>");
4.
5. if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"]){
6.
$prep = mysqli_prepare($DBconnection,'SELECT files.FILE_STORE,
files.FILE_TYPE FROM files JOIN applications ON files.appid = applications.appid JOIN
users ON users.userid=applications.userid WHERE (users.userid=? || "reviewer" = ? )
&& files.FILE_ID=?');
7.
mysqli_stmt_bind_param($prep,'sss',$_SESSION['userid'],$_SESSION['level'],
$_GET['itemid']);
8.
mysqli_stmt_execute($prep);
9.
mysqli_stmt_store_result($prep);
10.
11.
mysqli_stmt_bind_result($prep, $file, $filetype);
12.
mysqli_stmt_fetch($prep);
13.
14.
session_cache_limiter('no-cache');
15.
header('Content-type:'.$filetype);
16.
header('Content-Type:application-x/force-download');
17.
header('Content-Disposition: attachment; filename="$file"');
18.
header("Content-Transfer-Encoding: binary");
19. //
header('Content-Length: ' . filesize($file)); //
20. //
header("Cache-Control: no-store, no-cache, must-revalidate"); //
21.
header ("Cache-Control: post-check=0, pre-check=0", false);
22.
header("Cache-Control: max_age=0");
23.
header ("Pragma: no-cache");
24.
25. $file = @fopen($file,"rb");
26. if ($file) {
27. while(!feof($file)) {
28.
print(fread($file, 1024*8));
29.
flush();

30.
if (connection_status()!=0) {
31.
@fclose($file);
32.
die();
33.
}
34. }
35. @fclose($file);
36. }
37. //
echo $file; //
38. //
readfile($file); //
39.
40.
mysqli_stmt_free_result($prep);
41. }
42. else{
43. echo "You do not have permission to view this.";
44. }
45. ?>
help uploading and downloading files
from mysql database using php
Can anyone help me with my php script. i
have been trying to upload and download
files (images, pdfs etc) from mysql
database but i haven't been able to. i have
succeeded in uploading but the problem
now is to download. i have used this code
<?
//connect to the database
include "dbaseConnection.php";
$query = "SELECT * FROM images WHERE
id = 1";
$result = mysql_query($query) or
die(mysql_error());
// define results into variables
$name=mysql_result($result,0,"name");
$size=mysql_result($result,0,"size");
$type=mysql_result($result,0,"type");
$content=mysql_result($result,0,"content")
;
// give our picture the proper
headers...otherwise our page will be
confused
header("Content-Disposition: attachment;
filename=$name");
header("Content-length: $size");
header("Content-type: $type");
echo $content;
mysql_close();
?>
but its not giving me any results.
can anyone help me please? _

S-ar putea să vă placă și