3. •PHP and MySQL are tricky to teach without access to a
server and a database. We'll do the best we can in the
slides that follow.
•They are also tricky considering how complex they are.
Take a look at the PHP cheat sheet I found online...
3
4. PHP Introduction
•PHP is a recursive acronym for “PHP: Hypertext
Preprocessor” -- It is a widely-used open source
general-purpose scripting language that is especially
suited for web development and can be embedded
into HTML.
4
5. PHP History
• 1994: Created by Rasmis Lesdorf, software engineer
(part of Apache Team)
• 1995: Called Personal Home Page Tool, then released as
version 2 with name PHP/FI (Form Interpreter, to
analyze SQL queries)
• Half 1997: used by 50,000 web sites
• October 1998: used by 100,000 websites
• End 1999: used by 1,000,000 websites
5
6. Alternatives to PHP
• Practical extraction and Report Language (Perl)
• Active Server Pages (ASP)
• Java server pages (JSP)
• Ruby
6
7. (Good) Topics about PHP
• Open-source
• Easy to use ( C-like and Perl-like syntax)
• Stable and fast
• Multiplatform
• Many databases support
• Many common built-in libraries
• Pre-installed in Linux distributions
7
8. PHP Introduction
•> PHP is a server-side scripting language
•> PHP scripts are executed on the server
•> PHP supports many databases (MySQL, Informix,
Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)
•> PHP is open source software
•> PHP is free to download and use
8
9. PHP Introduction
•> PHP runs on different platforms (Windows, Linux,
Unix, etc.)
•> PHP is compatible with almost all servers used today
(Apache, IIS, etc.)
•> PHP is FREE to download from the official PHP
resource: www.php.net
•> PHP is easy to learn and runs efficiently on the server
side
9
10. PHP Introduction
•Some info on MySQL
•> MySQL is a database server
•> MySQL is ideal for both small and large applications
•> MySQL supports standard SQL
•> MySQL compiles on a number of platforms
•> MySQL is free to download and use
10
11. PHP Introduction
•Instead of lots of commands to output HTML (as seen
in C or Perl), PHP pages contain HTML with embedded
code that does "something" (like in the next slide, it
outputs "Hi, I'm a PHP script!").
•The PHP code is enclosed in special start and end
processing instructions <?php and ?> that allow you to
jump into and out of "PHP mode."
11
13. PHP Introduction
•PHP code is executed on the server, generating HTML
which is then sent to the client. The client would
receive the results of running that script, but would not
know what the underlying code was.
•A visual, if you please...
13
15. How PHP generates
HTML/JS Web pages
1: Client from browser send HTTP request (with POST/GET
variables)
2: Apache recognizes that a PHP script is requested and sends
the request to PHP module
3: PHP interpreter executes PHP script, collects script output
and sends it back
4: Apache replies to client using the PHP script output as HTML
output
2
Client
Browser
1 PHP
module
3
4
Apache
15
16. Hello World! (web oriented)
•<html>
•<head>
• <title>My personal Hello World! PHP script</title>
•</head>
•<body>
•<?
•echo “Hello World!”;
•?>
•</html>
PHP tag, allow to insert PHP
code. Interpretation by PHP
module will substitute the
code with code output
16
17. PHP Getting Started
•On windows, you can download and install WAMP.
With one installation and you get an Apache webserver,
database server and php.
•http://www.wampserver.com
•On mac, you can download and install MAMP.
•http://www.mamp.info/en/index.html
17
20. PHP Hello World
•This program is extremely simple and you really did
not need to use PHP to create a page like this. All it
does is display: Hello World using the PHP echo()
statement.
•Think of this as a normal HTML file which happens to
have a set of special tags available to you that do a lot
of interesting things.
20
21. PHP Comments
•In PHP, we use // to make
a single-line comment or /*
and */ to make a large
comment block.
21
22. PHP Variables
•> 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:
22
23. PHP Variables
•> 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.
23
24. PHP Variables
•> A variable name must start with a letter or an
underscore "_" -- not a number
•> A variable name can only contain alpha-numeric
characters, 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)
24
25. PHP Concatenation
•> The concatenation operator (.) is used to put two
string values together.
•> To concatenate two string variables together, use the
concatenation operator:
25
26. PHP Concatenation
•The output of the code on the last slide will be:
•If we look at the code 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.
26
27. PHP Operators
•Operators are used to operate on values. There are
four classifications of operators:
• > Arithmetic
• > Assignment
• > Comparison
• > Logical
27
32. PHP Conditional Statements
•> Very often when you write code, you want to
perform different actions for different decisions.
•> You can use conditional statements in your code to
do this.
•> In PHP we have the following conditional
statements...
32
33. PHP Conditional Statements
•> if statement - use this statement to execute some
code only if a specified condition is true
•> if...else statement - use this statement to execute
some code if a condition is true and another code if the
condition is false
•> if...elseif....else statement - use this statement to
select one of several blocks of code to be executed
•> switch statement - use this statement to select one
of many blocks of code to be executed
33
35. PHP Conditional Statements
•Use the if....else statement to execute some code if a
condition is true and another code if a condition is
false.
35
36. PHP Conditional Statements
•If more than one line
should be executed if a
condition is true/false, the
lines should be enclosed
within curly braces { }
36
37. PHP Conditional Statements
•The following example
will output "Have a nice
weekend!" if the current
day is Friday, and "Have a
nice Sunday!" if the
current day is Sunday.
Otherwise it will output
"Have a nice day!":
37
39. PHP Conditional Statements
•For switches, first we have a single expression n (most
often a variable), that is evaluated once.
•The value of the expression is then compared 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.
39
41. PHP Arrays
•> An array 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.
41
42. PHP Arrays
•If you have a list of items (a list of car names, for
example), storing the cars in single variables could look
like this:
42
43. PHP Arrays
•> 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 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.
43
44. PHP Arrays
• 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 arrays
44
45. PHP Numeric Arrays
•> A numeric array stores each array element with a
numeric index.
•> There are two methods to create a numeric array.
45
46. PHP Numeric Arrays
•In the following example the index is automatically
assigned (the index starts at 0):
•In the following example we assign the index
manually:
46
47. PHP Numeric Arrays
•In the following example you access the variable
values by referring to the array name and index:
•The code above will output:
47
48. PHP Associative Arrays
•> With 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.
48
49. PHP Associative Arrays
•In this example we use an array to assign ages to the
different persons:
•This example is the same as the one above, but shows
a different way of creating the array:
49
51. PHP 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.
51
55. PHP Loops
•> Often when you write code, you want the same
block of code to run over and over again in a row.
Instead of adding several almost equal lines in a script
we can use loops to perform a task like this.
•> In PHP, we have the following looping statements:
55
56. PHP Loops
•> while - loops through a block of code while a
specified condition is true
•> do...while - loops through a block of code once, and
then repeats the loop as long as a specified condition is
true
•> for - loops through a block of code a specified
number of times
•> foreach - loops through a block of code for each
element in an array
56
57. PHP Loops - While
•The while loop executes a block of code while a condition
is true. The example below defines a loop that starts with
•i=1. The loop will
•continue to run as
•long as i is less
•than, or equal to 5.
•i will increase by 1
•each time the loop
•runs:
57
59. PHP Loops – Do ... While
•The do...while statement will always execute the block
of code once, it will then check the condition, and
repeat the loop while the condition is true.
•The next example defines a loop that starts with i=1. It
will then increment i with 1, and write some output.
Then the condition is checked, and the loop will
continue to run as long as i is less than, or equal to 5:
59
63. PHP Loops - For
• Parameters:
• > init: Mostly used to set a counter (but can be any
code to be executed once at the beginning of the
loop)
• > condition: Evaluated for each loop iteration. If it
evaluates to TRUE, the loop continues. If it evaluates
to FALSE, the loop ends.
• > increment: Mostly used to increment a counter (but
can be any code to be executed at the end of the
loop)
63
64. PHP Loops - For
•The example below defines a loop that starts with i=1.
The loop will continue to run as long as i is less than, or
equal to 5. i will increase by 1 each time the loop runs:
64
66. PHP Loops - Foreach
•For every loop iteration, the value of the current array
element is assigned to $value (and the array pointer is
moved by one) - so on the next loop iteration, you'll be
looking at the next array value.
66
67. PHP Loops - Foreach
•The following example demonstrates a loop that will
print the values of the given array:
67
69. PHP Functions
•> We will now explore 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.
69
70. PHP Functions
•A function will be executed by a call to the function.
•> Give the function a name that reflects what the
function does
•> The function name can start with a letter or
underscore (not a number)
70
72. PHP Functions - Parameters
• 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.
72
77. PHP Forms - $_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 (max. 100 characters).
77
78. PHP Forms - $_GET Function
Notice how the URL carries the information after the file name.
78
79. PHP Forms - $_GET Function
•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)
79
80. PHP Forms - $_GET Function
•> When using method="get" in HTML forms, all
variable names and values are displayed in the URL.
•> 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.
•> The get method is not suitable for large variable
values; the value cannot exceed 100 chars.
80
81. PHP Forms - $_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).
81
82. PHP Forms - $_POST Function
And here is what the code of action.php might look like:
82
83. PHP Forms - $_POST Function
•Apart from htmlspecialchars() and (int), it should be
obvious what this does. htmlspecialchars() makes sure
any characters that are special in html are properly
encoded so people can't inject HTML tags or Javascript
into your page.
•For the age field, since we know it is a number, we can
just convert it to an integer which will automatically get
rid of any stray characters. The $_POST['name'] and
$_POST['age'] variables are automatically set for you
by PHP.
83
84. PHP Forms - $_POST Function
• 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.
84
91. Querying a Table
Syntax:
SELECT <field_list> FROM <table_name>
[ WHERE <condition> ];
Example:
SELECT * FROM student;
SELECT * FROM student WHERE st_age > 20;
91
92. Inserting a Record
Syntax:
INSERT INTO `table_name` (<fieldlist>) VALUES
(<valuelist>};
Example:
INSERT INTO student (st_fname, st_age) VALUES
( ‘Ahmad Albab’, 20 );
92
93. Updating a Record
Syntax:
UPDATE table_name SET <field value list>
[ WHERE <condition> ];
Example:
UPDATE student
SET
st_fname = ‘Jat’,
st_age = 22
WHERE st_id = 1;
93
94. Deleting a Record or Records
Syntax:
DELETE FROM table_name [ WHERE <condition> ];
Example:
DELETE FROM student WHERE st_id = 2;
DELETE FROM student WHERE st_age < 18;
94
95. PHP Functions for MySQL
PHP Function Description
mysql_connect() Connect to a MySQL database server
mysql_select_db() Make a database active
mysql_query() Execute SQL statement on active database
mysql_fetch_array()
Fetch a row from query result and return as
data as an array of fields and values
mysql_insert_id()
Returns the last inserted ID from an
auto_increment field
mysql_error() Returns the last MySQL error message.
95
97. mysql_connect()
• mysql_connect()
• The mysql_connect()function opens a non-persistent MySQL
connection.
• This function returns the connection on success, or FALSE and an
error on failure. You can hide the error output by adding an '@' in
front of the function name.
• Syntax
• mysql_connect(server,user,pwd,newlink,clientfla
g)
97
98. mysql_connect()
Parameter Description
server Specifies the server to connect to
user Specifies the username to log in with.
pwd Specifies the password to log in with.
newlink If a second call is made to mysql_connect() with the same arguments,
no new connection will be established; instead, the identifier of the
already opened connection will be returned
clientflag •MYSQL_CLIENT_SSL - Use SSL encryption
•MYSQL_CLIENT_COMPRESS - Use compression protocol
•MYSQL_CLIENT_IGNORE_SPACE - Allow space after function names
•MYSQL_CLIENT_INTERACTIVE - Allow interactive timeout seconds of
inactivity before closing the connection
98
99. MySQL Connectivity
• Example:
• <?php
$con =
mysql_connect("localhost","mysql_user","mysq
l_pwd");
if (!$con){
die('Could not connect: ‘.mysql_error());
}
echo 'Connected successfully';
mysql_close($con);
• ?>
99
100. MySQL Connectivity
• mysql_close()
• The mysql_close() function closes a non-persistent MySQL
connection.
• This function returns TRUE on success, or FALSE on failure.
• Syntax:
• mysql_close(connection)
Parameter Description
connection Specifies the MySQL connection to close. If not
specified, the last connection opened by
mysql_connect() is used.
100
101. Try out following example to open and close a database connection
• <?php
• $dbhost = 'localhost:3036';
• $dbuser = 'guest';
• $dbpass = 'guest123';
• $conn = mysql_connect($dbhost, $dbuser,
$dbpass);
• if(! $conn ) {
• die('Could not connect: ' .
mysql_error()); }
• echo 'Connected successfully';
• mysql_close($conn);?>
101
103. mysql_select_db()
• mysql_select_db()
• The mysql_select_db() function sets the active MySQL database.
• This function returns TRUE on success, or FALSE on failure.
• Syntax:
• mysql_select_db(database,connection)
Parameter Description
database Required. Specifies the database to select.
connection Optional. Specifies the MySQL connection. If not
specified, the last connection opened by
mysql_connect() or mysql_pconnect() is used.
103
104. mysql_select_db()
• <?php
$con = mysql_connect("localhost", “root",
“admin");
if (!$con){
die('Could not connect: '. mysql_error());
}
$db_selected = mysql_select_db("test_db",
$con);
if (!$db_selected){
die ("Can't use test_db : “.
mysql_error());
}
mysql_close($con);
• ?>
104
105. Example showing you how to select a database
• <?php
• $dbhost = 'localhost:3036';
• $dbuser = 'guest';
• $dbpass = 'guest123';
• $conn = mysql_connect($dbhost, $dbuser, $dbpass);
• if(! $conn ) {
• die('Could not connect: ' . mysql_error());
• }
• echo 'Connected successfully';
• mysql_select_db( 'test_db' );
• mysql_close($conn);
• ?>
105
107. mysql_query()
• mysql_query()
• The mysql_query() function executes a query on a MySQL
database.
• This function returns the query handle for SELECT queries,
TRUE/FALSE for other queries, or FALSE on failure.
• Syntax
• mysql_query(query,connection)
Parameter Description
query Required. Specifies the SQL query to send (should not
end with a semicolon)
connection Optional. Specifies the MySQL connection. If not
specified, the last connection opened by
mysql_connect() or mysql_pconnect() is used. 107
108. Try out following example to create a database
• <?php
• $dbhost = 'localhost:3036';
• $dbuser = 'root';
• $dbpass = 'rootpassword';
• $conn = mysql_connect($dbhost, $dbuser, $dbpass);
•
• if(! $conn ) {
• die('Could not connect: ' . mysql_error());
• }
• echo 'Connected successfully';
•
108
110. MySQL Connectivity
• <?php
$con =
mysql_connect("localhost",”root",”admin");
if (!$con){
die('Could not connect: ' . mysql_error());
}
$sql = "CREATE DATABASE my_db";
if (mysql_query($sql,$con)){
echo "Database my_db created";
}
else{
echo "Error creating database:" .
mysql_error();
}
• ?>
110
111. MySQL Connectivity
• <?php
$con = mysql_connect("localhost", “root",
“admin");
if (!$con){
die('Could not connect: '. mysql_error());
}
$db_selected = mysql_select_db("test_db", $con);
if (!$db_selected){
die ("Can't use test_db : “. mysql_error());
}
• $sql="SELECT * FROM Person where
name=‘$uname’";
mysql_query($sql,$con);
mysql_close($con);
• ?>
111
113. •mysql_fetch_array()
• mysql_fetch_array()
• 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)
113
114. mysql_fetch_array()
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
114
115. mysql_fetch_row()
• mysql_fetch_row()
• 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
115
120. Include Files
• include “header.php”;
• include (“footer.php”);
• This inserts files; the code in files will be inserted into current code.
• require is identical to include except upon failure it will
also produce a fatal E_COMPILE_ERROR level error.
• In other words, it will halt the script whereas include only
emits a warning (E_WARNING) which allows the script to
continue.
120
121. Include Files
• The include_once statement includes and evaluates the
specified file during the execution of the script.
• This is a behavior similar to the include statement, with the only
difference being that if the code from a file has already been
included, it will not be included again.
• The require_once statement is identical to require except
PHP will check if the file has already been included, and if so, not
include (require) it again
121
124. Cookies
• The setcookie() function is used to create cookies. Should be called before
<html> tag.
• setcookie(name, [value], [expire], [path], [domain],
[secure]);
• <?php setcookie("uname", $name, time()+36000); ?>
• This sets a cookie named "uname" - that expires after ten hours.
• Either a blank value or a time in the past makes the cookie expired.
124
125. Cookies
• To access a cookie, refer to the cookie name as a variable or use
$_COOKIE array. The isset() checks whether the cookie is set
or not
<html> <body>
<?php
if (isset($uname))// isset($_Cookie[$uname])
echo "Welcome " . $_Cookie[$uname].
"!<br />";
else
echo "You are not logged in!<br />"; ?>
?>
</body> </html>
125
126. Cookies
•Benefit of Cookies
• Cookies are used for authenticating, tracking, and maintaining specific
information about users
• Personalised home pages
• Electronic shopping carts.
126
127. Why use sessions
• A normal HTML website will not pass data from one
page to another
• All information is forgotten when a new page is
loaded
• Many websites need to pass user data from one page
to another
• for tasks like a shopping cart, which requires data(the user's
selected product) to be remembered from one page to the next
• Using PHP sessions is one solution.
127
128. Sessions
• The session_start() function is used to create a session.
Should be called before
• <html> tag.
<?php
session_start();
?>
128
131. mysql_connect() & Mysqli_connect
• MySQLi provides a object-oriented way for accessing MySQL
databases.
• if you use mysql_query(),
• you should use mysql_connect() to connect to your server.
• Mysqli_connect is the newer version of mysql library
131