Internet & WWW How to program Chap.(23 4 Ed.)

advertisement
Internet & WWW
How to program
Chap.(23 4th Ed.)
PHP (Personal Home Page)
Dr. Qusai Abuein
1
(23.1) Introduction
• PHP is platform independent; implementations exist for all
major UNIX, Linux and Windows operating systems.
• PHP also support a large number of databases, including
MySQL.
• We study:
– basics of the scripting languages
– viewing environment variables
– form processing and business logic
– implementing a private Web site through username and password
verifications
– application that queries a MySQL database
– use cookies to store information
– form-processing
Dr. Qusai Abuein
2
(23.2) PHP Basics
• PHP was written specifically for interacting with the Web:
– not only serving content to users, but also responding to
requests from users
– generating Web pages with dynamic content
• PHP code is embedded directly into XHTML documents. This
allows the document author to write XHTML in a clear, concise
manner, without having to use multiple print statements, as is
necessary with other CGI-based languages.
• PHP script file names usually end with .php, although a server
can be configured to handle other file extensions.
• To run a PHP script, PHP must first installed on your system.
• For this chapter’s examples to run correctly, you might need to
copy it to: (C:\Program Files\Apache Group\Apache2\htdocs) for
those who are using Apache .
Dr. Qusai Abuein
3
(23.2) PHP Basics
• Figure 23.1 (first.php) presents a simple PHP program that
displays a welcome message.
• In PHP, code is inserted between the scripting delimiters <?php
and ?>.
• PHP code can be placed anywhere in XHTML markup, as long
as the code is enclosed in these scripting delimiters.
• All variables are preceded by $ and are case sensitive:
– $name != $Name
• PHP statements are terminated with a semicolon ( ; ).
Dr. Qusai Abuein
4
(23.2) PHP Basics
• one-line comment (//, #). See line 8.
• Multiline comments begin with delimiter /* and end with
delimiter */
• Line 21 outputs the value of variable $name by calling function
print.
• When a variable is encountered inside a double-quoted (“”)
string, PHP interpolates the variable.
• PHP variables are “multitype,” meaning that they can contain
different types of data (e.g., integers, doubles or strings) at
different times. Figure 23.1 (first.php) introduces theses data
types.
Dr. Qusai Abuein
5
(23.2) PHP Basics
• Boolean variables:
– $a = true; // do not use quotes , $b = 1; is evaluated to true
– $c = false; // d = 0; is evaluated to false
• PHP variable names are case sensitive.
• Function names are case insensitive.
• Constants names are according to the user definition.
Dr. Qusai Abuein
6
(23.2) PHP Basics
• Data types in PHP can be found in Figure 32.2.
–
–
–
–
–
–
–
–
int, integer
float, double, real
string
bool, boolean
array
object
resource
NULL (no value)
Dr. Qusai Abuein
7
(23.2) Converting Between PHP Data Types
• Conversion between different data type may be necessary when
performing arithmetic operations with variables. In PHP datatype conversion can be performed by passing the data type as an
argument to function settype. See Figure 23.3 (data.php).
• Function settype tack two arguments:
– the variable whose data is to be changed and
– the variable’s new data type.
• Another option for conversion between types is casting (or type
casting). Unlike settype, casting doesn’t change a variable’s
content. Rather, type casting creates a temporary copy of a
variables value in memory.
• The concatenation operator (.) concatenates strings. Line 47 –
50.
Dr. Qusai Abuein
8
(23.2) Arithmetic operators
• Fig.23.4 (operators.php) demonstrates a variety of arithmetic
operators in PHP.
• Line 18 calls function define to create a named constant.
• A constant is a value that cannot be modified once it is declared.
• Function define tacks two arguments:
– the name (without $) and
– the value of the constant.
• An optional third argument accepts a Boolean value that specifies
whether the constant is case insensitive—constants are case
sensitive by default.
Dr. Qusai Abuein
9
(23.2) Arithmetic operators
• In PHP, uninitialized variables have the value undef, which
evaluates to different values, depending on its context. For
example:
– when undef is used in a numeric context (e.g., $num in line 54), it
evaluates to 0.
– when undef is interpreted in a string context (e.g., $nothing in line 51), it
evaluates to an empty string (“”).
• Strings are converted to integers when they are used in arithmetic
operation (lines 59-60).
Dr. Qusai Abuein
10
(23.2) Arithmetic operators
•
•
•
•
•
•
//Addition: $a + b = 6
//Subtraction: $a - $b = 2
//Multiplication: $a * $b = 8
//Division :$a / $b = 2
//Modulus (remainder of $a / $b): $a % $b = 0
//Increment: $a++ (would equal 5 since $a = 4)
• Comparison Operators :
–
–
–
–
–
–
$a == $b test if two values are equal
$a != $b test if two values are not equal
$a < $ b test if the first value is less than the second
$a > $b test if the first value is greater than the second
$a <= $b test if the first value is less than or equal to the second
$a >= $b test if the first value is greater than or equal to the second
Dr. Qusai Abuein
11
(23.2) PHP Keywords
• Figure 23.5, contains the keywords.
–
–
–
–
–
–
–
–
Exit
Die
Do
Isset
Array
Echo, print
Default
Function
Dr. Qusai Abuein
12
Switch Statements
$a = "100";
switch($a)
{
case(10): print ( "The value is 10“) ;
break;
case (100): print( "The value is 100<br/>“);
break;
case (1000): print( "The value is 1000“);
break;
default: print( "<p>Are you sure you entered a number?“);
}
Dr. Qusai Abuein
13
While and Do WhileLoops
While (condition)
{
statement(s);
}
---------------$i = 0;
do
{
print $i;
} while ($i>0);
Dr. Qusai Abuein
14
(23.2) Initializing and manipulating Arrays
•
Arrays are divided into elements that behave as individual
variables. Array names, like other variables, begin with the
$ symbol. See Fig.23.6 (arrays.php).
•
Individual array elements are accessed by following the array-variable
name with an index (starting at 0) enclosed in braces ([]).
•
If a value is assigned to an array that doesn’t exist, then the
array is created (lines 18,19,20).
•
assigning a value to an element where the index is omitted
appends a new element to the end of the array (line 21).
Function count (used in the for loop) returns the total number of
elements in the array.
Line 31 demonstrates a second method of initializing arrays.
Function array returns an array that contains the arguments
passed to it.
•
•
Dr. Qusai Abuein
15
(23.2) Initializing and manipulating Arrays
•
In addition to integer indices, arrays can have nonnumeric
indices (lines 39-41).
For example, indices ArtTic, LunaTic and GalAnt are
assigned the values 21, 18, 23, respectively.
PHP provides function for iterating through the elements of an
array (lines 45-46).
Each array has a built-in internal pointer, which points to the
array element currently begin referenced.
Function reset sets the internal pointer to the first element of the
array.
Function key returns the index of the element currently
referenced by the internal pointer:
•
•
•
•
•
–
•
•
$i = key(third); $third($i);
Function next moves the internal pointer to the next element.
The for loop continues to execute as long as function key
returns an index. Function next returns false when there are no
additional elements in the array.
Dr. Qusai Abuein
16
(23.2) Initializing and manipulating Arrays
•
•
•
•
Function array can also be used to initialize arrays with string
indices. In order to override the automatic numeric indexing
performed by function array, use operator (=>), as demonstrated
in lines 54-61.
The value to the left of the operator is the array index, and the
value to the right is the element’s value. An array with string
indices also is called an associative array.
The foreach loop (lines 64-65) is a control statement
that is specially designed for iterating through arrays.
The syntax for a foreach loop:
–
–
–
starts with the array to iterate through,
followed by the keyword as,
followed by the variables to receive the index and the value
for each element.
Dr. Qusai Abuein
17
(23.2) Initializing and manipulating Arrays
•
•
Text manipulation in PHP is usually done with regular
expressions.
regular expressions are a series of characters that serve as
pattern-matching templates (or search criteria) in strings, text
files and databases.
Dr. Qusai Abuein
18
(23.3) String Processing and Regular Expressions
•
Comparing Strings:
•
Line 23 and 25 of Fig.23.7 (compare.php) call function strcmp
to compare two strings:
–
–
–
If the first string alphabetically precedes the second string, then -1 is
returned.
If the strings are equal, then 0 is returned.
If the first string alphabetically follows the second string, then 1 is
returned
Dr. Qusai Abuein
19
(23.3) String Processing and Regular Expressions
•
Relational operators (= =,! =, <, <=, >, >=) can also be used to
compare strings. These operators are also used for numerical
comparison with integers and doubles.
•
Using Regular Expressions
•
PHP provides function ereg, which uses regular expressions to search
a string for a specified pattern (return false if not matched or the
length of the matched string)
eregi for case sensitive pattern match.
Figures (23.9, 23.10) contains some PHP quantifiers and character
classes.
{n}, {m,n}, {n,}, +, *, ?
alnum, alpha, digit, space, lower, upper
•
•
•
•
Dr. Qusai Abuein
20
(23.3) String Processing and Regular Expressions
•
•
•
•
•
Figure 23.8 (expression.php) demonstrates some of PHP’s regular
expressions capabilities.
Line 14 assigns the string “Now is the time” to variable $search
Line 19 calls function ereg to search for the literal characters “Now”
inside variable $search. If(ereg(“Now”, $search))
If the pattern is found, ereg returns true.
Function ereg tacks two arguments-a regular expression pattern to
search for (Now) and the string to search. And an optional third one as
an array to hold the results.
Dr. Qusai Abuein
21
(23.3) String Processing and Regular Expressions
•
•
•
•
Function ereg is a case sensitive and searches only for the first
occurrence.
PHP provides function eregi for specifying case-insensitive
pattern matches.
In addition to literal characters, regular expressions can include
special characters called (metacharacters ) that specify patterns.
For example:
– The caret (^) special character matches the beginning of a string. Line 24
–
A dollar sign ($) search for the specified pattern at the end of the string (line 29)
–
The period (.), which matches any single characters
If the third argument of preg is mentioned , then the first match
of the string is stored in the second element of the array and the
second match is stored in the third element and so on. The first
element (index 0) contains the whole matched string. Line 34.
Dr. Qusai Abuein
22
(23.3) String Processing and Regular Expressions
•
Searching for multiple instances of a pattern in a string is
slightly more complicated, because the ereg function matches
only the first instance of the pattern.
To find multiple instances of a given pattern, we must remove
any matched instances before calling ereg again.
Lines 42-49 use a while loop and the ereg_replace function to
find all the words in the string that begins with t.
Function ereg_replace tacks three arguments:
•
•
•
–
–
–
•
the pattern to match,
a string to replace the matched string and
the string to search.
The modified string is returned , so line 48 uses $search to store
the returned string allowing us to search for another match. The
new $search string now does not contain the first matched string.
Dr. Qusai Abuein
23
User-Defined Functions
function check_age($age) {
if ($age > 21) {
return 1; }
else { return 0; }
}
//usage:
if(check_age($age)) {
print ("You may enter!“);
} else
{ print( "Access Not Allowed!“); exit;
}
Dr. Qusai Abuein
24
(23.4) Form Processing and Business Logic
•
One way to obtain data sent by client (user entry through forms)
to server is by using Superglobal Arrays.
•
Superglobal arrays are associative arrays predefined by PHP
that hold variables acquired from user input, the environment or
the web server, and are accessible in any variable scope.
•
•
Some PHP superglobal arrays are listed in Figure 23.11.
$_SERVER, $_ENV, $_GET, $_POST, $_COOKIE,
$GLOBALS
Dr. Qusai Abuein
25
(23.4) Form Processing and Business Logic
•
•
•
•
•
XHTML form enables Web pages to collect data from users
and send it to a Web server for processing. Interaction of these
kinds between users and Web servers is vital to e-commerce
applications.
Figure 23.12 (FORM.HTML) uses an XHTML form to collect
information about users for the purpose of adding them to a
mailing list.
The action attribute of the form element (line 18) indicates that
when the user clicks the Register (Submit) button, the form
data will be posted to form.php (Fig. 26.14) for processing.
Using method = “post” appends form data to the browser
request that contains the protocol (i.e., HTTP) and the requested
recourse’s URL.
Scripts located on the web server’s machine can access the form
data sent as part of the request.
Dr. Qusai Abuein
26
(23.4) Form Processing and Business Logic
•
•
•
•
•
•
We assign a unique name (e.g., email) to each of the form’s
input fields.
When Register is clicked, each fields name and value is sent to
the Web server.
Script form.php can then access the value for each specific field
through the superglobal array $_POST.
Superglobal arrays are associative arrays predefined by PHP
that hold variables acquired from the user input, the
environment or the Web server and are accessible in variable
scope. The $_ENV array used in Fig. 23.13 is another example
of superglobal array.
$_POST contains key-value pairs corresponding to name-value
pairs for variables submitted through the form. [Note: The
superglobal array $_GET would contain these key-value pairs if
the form had been submitted using the HTTP get method].
Figure 23.13 (form.php) processes the data posted by
form.html and sends XHTML back to the client.
Dr. Qusai Abuein
27
(23.4) Form Processing and Business Logic
•
•
•
•
•
•
•
•
Function extract (associativeArray) (line 15) creates a variable-value
pair corresponding to each key-value pair in the associativeArray (i.e.,
$_POST), creating variables whose respective names and values
corresponding to the names and variables of each posted form field.
For example, in line 36 of Fig. 23.12, an XHTML text box is created
and given the name email.
In line 70 of our PHP script (Fig. 23.13), after having called function
extract, we access the field’s value by using variable $email.
Elements in the superglobal array $_POST also can be accessed using
standard array notation. For example, we could have accessed the
form field email’s value by referring to $_POST[‘email’].
See Good Programming Practice tip 23.1 page 925.
$_POST[‘email’] is more secure than $email.
Function die() (line 43) terminates script execution. In this case, if
the user did not enter a correct value, we do not want to continue
executing the rest of the script, so we call function die().
See Error_Prevention Tip 23.3 page 929.
Dr. Qusai Abuein
28
(23.5) Connecting to a Database
Using MySQLi Functions
•
PHP MySQLi = PHP MySQL Improved!
•
Figures 23.14 (data.html) and 23.15 (database.php) use
mysql function; which has been deprecated as of PHP
5.5.0
Dr. Qusai Abuein
29
(23.5) Connecting to a Database (mysqli_connect)
•
The MySQLi functions allows you to access
MySQL database servers.
1. mysqli_connect(): Opens a new connection to
the MySQL server
• Syntax
• mysqli_connect(host,username,password,dbname
,port,socket);
Dr. Qusai Abuein
30
(23.5) Connecting to a Database (mysqli_connect)
• mysqli_connect(host,username,password,dbname,port,socket);
•
Parameter
Description
host
Optional. Specifies a host name or an IP address
username
Optional. Specifies the MySQL username
password
Optional. Specifies the MySQL password
dbname
Optional. Specifies the default database to be used
port
Optional. Specifies the port number to attempt to connect to the
MySQL server
socket
Optional. Specifies the socket or named pipe to be used
Returns an object representing the connection
to the MySQL server
Dr. Qusai Abuein
31
(23.5) mysqli_connect_errno()
• <?php
$con =
mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection Object Oriented :
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
• Mysql_connect_errno(): Returns the error code from the last
connection error
Return Value:
Returns an error code value. Zero if no error occurred
Dr. Qusai Abuein
32
(23.5) mysqli_connect_err()
• <?php
$con =
mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection Structural programming
• if (!$con)
• {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
• mysqli_connect_error() function returns the error description
from the last connection error, if any.
Dr. Qusai Abuein
33
(23.5) mysqli_select_db()
• mysqli_select_db(): function is used to change the default
database for the connection.
• Syntax
• mysqli_select_db(connection,dbname);
connection
Required. Specifies the MySQL
connection to use
dbname
Required. Specifies the default database to
be used
Return Value:
TRUE on success. FALSE on failure
Dr. Qusai Abuein
34
(23.5) mysqli_select_db()
• <?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// ...some PHP code for database "my_db"...
// Change database to "test"
mysqli_select_db($con,"test");
// ...some PHP code for database "test"...
mysqli_close($con);
?>
• Note the connection “$con” argument of the connection parameter.
• mysqli_close() function closes a previously opened database connection.
Dr. Qusai Abuein
35
(23.5) mysqli_query()
• mysqli_query(): function performs a query (select, insert, update, delete)
against the database.
• Syntax
• mysqli_query(connection,query,resultmode);
Connection
Required. Specifies the MySQL connection to use
query
Required. Specifies the query string
resultmode
Optional. A constant. Either:
•MYSQLI_USE_RESULT (Use this if we have to retrieve
large amount of data)
•MYSQLI_STORE_RESULT (This is default)
Return Value:
For successful SELECT, SHOW, DESCRIBE, or EXPLAIN
queries it will return a mysqli_result object. For other successful
queries it will return TRUE. FALSE on failure
Dr. Qusai Abuein
36
(23.5) mysqli_query()
• <?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
mysqli_query($con,"SELECT * FROM Persons");
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)");
mysqli_close($con);
?>
Dr. Qusai Abuein
37
(23.5) mysqli_fetch_row
• mysqli_fetch_row(): function fetches one row from a result-set and returns it as
an enumerated array.
• Syntax
• mysqli_fetch_row(result);
• Result: Required. Specifies a result set identifier returned by mysqli_query().
Dr. Qusai Abuein
38
(23.5) mysqli_fetch_row
•
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
if ($result = mysqli_query($con,$sql))
{
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
printf ("%s (%s)\n",$row[0],$row[1]);
}
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
Dr. Qusai Abuein
39
(23.5) mysqli_fetch_array
• mysqli_fetch_array(): function fetches a result row as an associative array, a
numeric array, or both.
• Note: Fieldnames returned from this function are case-sensitive.
• Syntax
• mysqli_fetch_array(result,resulttype);
result
Required. Specifies a result set
identifier returned by mysqli_query(),
mysqli_store_result() or
mysqli_use_result()
resulttype
•Optional. Specifies what type of array
that should be produced. Can be one of
the following values:MYSQLI_ASSOC
•MYSQLI_NUM
•MYSQLI_BOTH
Return Value:
Returns an array of strings that corresponds to the fetched row.
NULL if there are no more rows in result-set
Dr. Qusai Abuein
40
(23.5) mysqli_fetch_array
•
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
$result=mysqli_query($con,$sql)
// Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
printf ("%s (%s)\n",$row[0],$row[1]);
// Associative array
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
printf ("%s (%s)\n",$row["Lastname"],$row["Age"]);
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>
Dr. Qusai Abuein
41
(23.5) mysqli_close()
• mysqli_close(): function closes a previously opened database connection.
• Syntax
• mysqli_close(connection);
• Connection: Required. Specifies the MySQL connection to close
Return Value:
TRUE on success. FALSE on failure
Dr. Qusai Abuein
42
(23.5) Useful Functions
• mysqli_errno(): function returns the last error code for the most recent function
call, if any.
• Syntax
• mysqli_errno(connection);
• connectionRequired. Specifies the MySQL connection to use
Return Value:
Returns an error code value. Zero if no error occurred
• // Perform a query, check for error
if (!mysqli_query($con,"INSERT INTO Persons (FirstName) VALUES
('Glenn')"))
{
echo("Errorcode: " . mysqli_errno($con));
}
Dr. Qusai Abuein
43
(23.5) Useful Functions
• mysqli_num_rows(): function returns the number of rows in a result set.
• Syntax
• mysqli_num_rows(result);
• Result:
Required. Specifies a result set identifier returned by
mysqli_query()
Return Value:
•
Returns the number of rows in the result set
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
printf("Result set has %d rows.\n",$rowcount);
// Free result set
mysqli_free_result($result);
Dr. Qusai Abuein
}
44
(23.5) Useful Functions
• mysqli_num_fields(): function returns the number of fields (columns) in a
result set.
• Syntax
• mysqli_num_fields(result);
• resultRequired. Specifies a result set identifier returned by mysqli_query()
Return Value:
Returns the number of fields in the result set
• $sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
// Return the number of fields in result set
$fieldcount=mysqli_num_fields($result);
printf("Result set has %d fields.\n",$fieldcount);
// Free result set
mysqli_free_result($result);
}
Dr. Qusai Abuein
45
(23.5) Connecting to DB using PDO
• The PHP Data Objects (PDO) extension defines a lightweight, consistent
interface for accessing databases in PHP. Each database driver that implements
the PDO interface can expose database-specific features as regular extension
functions.
• <?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?>
Dr. Qusai Abuein
46
String Functions
•
•
•
•
•
•
•
•
•
Strcmp
Str_split,
Explode
Count_chars
Implode, join
str_replace
Str_word_count
Strlen
Strtolower, strtoupper
Dr. Qusai Abuein
47
Array Functions
•
•
•
•
•
•
•
•
•
count
array_key_exists
array_product
array_pop, array_push
array_replace
array_reverse
array_splice
array_sum
sort, asort
Dr. Qusai Abuein
48
Array Functions
•
•
•
•
•
•
current
end
key
next
pos
prev
Dr. Qusai Abuein
49
End of Chap. (23)
Thank you .
Dr. Qusai Abuein
50
Download