Академический Документы
Профессиональный Документы
Культура Документы
PHP Engine
Run Script
HTML Response PHP Results
User Web Server
How to install PHP
Find a web host with PHP and MySQL support
Install a web server on your own PC, and then install PHP and
MySQL
History
Started as a Perl hack in 1994 by Rasmus Lerdorf
(to handle his resume), developed to PHP/FI 2.0
By 1997 up to PHP 3.0 with a new parser engine
by Zeev Suraski and Andi Gutmans
Current version: 7
php is one of the premier examples of what an
open source project can be
Unique Features
Performance:
Portability:
Ease of Use
Open Source
Community Support
Third Party Application Support
PHP - Syntax and Structure
PHP is similar to C
All scripts start with
<?php and with with ?>
Output
Comment
Comments are created using:
// single line quote
# This is also a single-line comment
/* Multiple line block quote */
// also used to leave out parts of a code line
<?php
$x = 5 /* + 15 */ + 5;
echo $x;
?>
What is a php file?
PHP files can contain text, HTML, CSS, JavaScript, and PHP
code
PHP code are executed on the server, and the result is
returned to the browser as plain HTML
PHP files have extension ".php"
Required Components
Operating System (Linux)
Webserver (usually Apache)
A database engine (such as MySQL)
PHP interpreter
PHP application for the Web:
the typical approach is to embed PHP code into one or more
standard HTML documents using special tags, or delimiters.
<!DOCTYPE html>
<html>
<body>
<?php
echo "My first PHP script!";
?>
</body>
</html>
PHP Case Sensitivity
In PHP, all keywords (e.g. if, else, while, echo, etc.), classes,
functions, and user-defined functions are NOT case-sensitive.
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
Escape Sequences
Complete Reference
PHP Frameworks
PHP Decision Making
$Count = 1;
while ($Count <= 10) {
}
do .. while Statement
Test the condition after executing a series of statements then
repeats the execution as long as a given conditional expression
evaluates to TRUE
The syntax for the do...while statement is :
do {
statement(s);
} while (conditional expression);
do .. while Statement
$Count = 2;
do {
echo " <p>The count is equal to
$Count</p> ";
++$Count;
} while ($Count < 2);
for Statement
Combine the initialize, conditional evaluation, and update
portions of a loop into a single statement
Repeat a statement or a series of statements as long as a given
conditional expression evaluates to TRUE
If the conditional expression evaluates to TRUE, the for
statement executes and continues to execute repeatedly until the
conditional expression evaluates to FALSE
for Statement
foreach ($array_name as
$variable_name) {
statements;
}
foreach Statement
Example :
$DaysOfWeek = array(("Monday",
"Tuesday",
"Wednesday", "Thursday", "Friday",
"Saturday", "Sunday");
foreach ($DaysOfWeek as $Day) {
echo "<p>$Day</p>";
}
for Statement
Combine the initialize, conditional evaluation, and update
portions of a loop into a single statement
Repeat a statement or a series of statements as long as a given
conditional expression evaluates to TRUE
If the conditional expression evaluates to TRUE, the for
statement executes and continues to execute repeatedly until the
conditional expression evaluates to FALSE
What Is Function ?
1) User-defined Function.
2) Built-in 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)
Create a PHP Function
Begins with keyword function and then the space and then the name of the
function then parentheses() and then code block {}
function functionName()
{
//code to be executed;
}
Create a PHP Function
We want our function to print out the company motto each time it's called,
<?php
function myfunction()
{
echo This is the first function to me ";
}
?>
Note: Your function name can start with a letter or underscore "_", but not a number!
Call Function - Example
<?php
function myfunction()
{
echo Muneer Masadeh";
}
echo my name is ;
myfunction();
?>
Parameters Functions
<?php
function myfunction($par1, $par2 ,..)
{
echo This is the first function with parameters to me ";
}
?>
Parameters Functions
<?php
function myname($firstName)
{
echo my name is ". $firstName ;
}
?>
Parameters Functions Call
<?php
function myname($firstName)
{
echo my name is ". $firstName . "!<br />";
}
myname(kalid");
myname("Ahmed");
myname(laith");
myname(muneer");
?>
Parameters Functions - Call
<?php
function myname($firstName, $lastName)
{
echo "Hello there ". $firstName ." ". $lastName ."!<br />";
}
myname(Kalid", Ali");
myname("Ahmed", Samer");
myname(Wael", Fadi");
myname(Muneer", " Masadeh");
?>
Parameters Functions - Call
<?php
function writeName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "<br />";
}
echo "My name is ";
writeName(muneer ",".");
echo "<br>My family's name is ";
writeName(" Masadeh ",,");
echo <br>I am Dr in ";
writeName(CS Department ",!");
?>
Function Returning Values
In addition to being able to pass functions information, you can also have
them return a value. However, a function can only return one thing,
although that thing can be any integer, float, array, string, etc. that you
choose!
How does it return a value though? Well, when the function is used and
finishes executing, it sort of changes from being a function name into being
a value. To capture this value you can set a variable equal to the function.
Something like:
$myVar = somefunction();
Functions Returning Values Example
<?php
function mySum($numX, $numY)
{
return ($numX + $numY);
}
$myNumber = 0;
echo "Before call function, myNumber = ". $myNumber ."<br />";
// Store the result of mySum in $myNumber
$myNumber = mySum(3, 4);
echo "After call function, myNumber = " . $myNumber ."<br />";
?>
Function Returning Values Example
<?php
function factorial($number)
{
$ temp = 0;
if($number <= 1)
return 1;
$temp = $number * factorial($number - 1);
return $temp;
}
$ number = 4;
if ($number < 0)
echo "That is not a positive integer.\n";
else
echo $number . " factorial is: " . factorial($number);
?>
Function Returning Values Example
<?php
$n = 10;
echo " The sum is . sum($n) ;
function sum($a)
{
if ( $n <= 0 )
return 0;
else
return ($n + sum($n-1));
}
?>
Function returning arrays
function create_array($no)
{
for ($i=0;$i<$no;$i++)
{
$arr[]=$i;
}
return $arr;
}
Passing Variable to a function
<?php
$numX = 1;
function byvalue ($numX)
{
$numX = $numX + 1;
}
byvalue ($numX);
echo the change after send data by value = ". $numX ."<br />";
?>
Passing Variable By Reference
<?php
function byreference (&$numX)
{
$numX = $numX + 1;
}
byvalue ($numX);
echo the change after send data by Reference = ". $numX ."<br />";
?>
Passing Variable By Reference
<?php
function foo(&$var)
{
$var++;
}
$a=5;
echo foo($a); // $a is 6 here
?>
PHP Variable Scopes
<?php
$x=5; // global scope
function myTest()
{
echo $x; // local scope
}
myTest();
?>
Local Scope
The script above will not produce any output because the echo
statement refers to the local scope variable $x, which has not been
assigned a value within this scope.
You can have local variables with the same name in different functions,
because local variables are only recognized by the function in which they
are declared.
<?php
$x=5; // global scope
$y=10; // global scope
function myTest()
{
global $x,$y;
$y=$x+$y;
}
myTest();
echo $y; // outputs 15
?>
Global Scope
<?php
$x=5;
$y=10;
function myTest()
{
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
}
myTest();
echo $y;
?>
Static Scope
To do this, use the static keyword when you first declare the
variable:
Static Scope
<?php
function myTest()
{
static $x=0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Static Scope
<?php
function myTest($x)
{
echo $x;
}
myTest(5);
?>
Working with Forms
1. Creating a form
2. Accessing the submitted data
3. Common operations on forms
1 - Creating a form
Form - <form>
This element defines a form that is used to collect user input
...
</form>
action = URL
method = get | post
http://www.w3schools.com/tags/tag_form.asp
Text field - <input>
For single line text input:
http://www.w3schools.com/tags/tag_input.asp
Password - <input>
For single line masked text input
</form>
Drop-down list
<select><option>
Single choice
<textarea name="myTextArea"
cols="30"
rows="5">
</textarea>
http://www.w3schools.com/tags/tag_textarea.asp
Hidden fields - <input>
To send information with the form
<input type="hidden"
name="hidden1"
value="Form example for demo"/>
Button - <input> or <button>
<input type="submit"
name="submitButton"
value="Submit Form"/>
<button type="submit"
name="submitButton">
SubmitForm
</button>
2 - How does one access the submitted data?
Using PHP
Data stored in a variable
Depends on submission method:
GET
POST
If POST, either:
$varName (requires special configuration)
$_POST['varName'] (recommended)
$HTTP_POST_VARS['varName']
If GET, use:
$_GET['varName']
Difference between GET &
POST
GET POST
Parameters remain in browser Parameters are not saved
history because they are part of in browser history.
the URL
Can be bookmarked.
Can not be bookmarked.
can send but the parameter Can send parameters,
data is limited to what we can including uploading files, to
stuff into the request line (URL). the server.
Safest to use less than 2K of More difficult to hack
parameters, some servers
handle up to 64K POST method used when
Easier to hack for script kiddies sending passwords or
GET method should not be other sensitive
used when sending passwords information.
or other sensitive information. Can not be cached
Can be cached
Two basic approaches
Approach 1
HTML form
PHP script to process it
Approach 2
PHP script containing the form and the processing script:
<form action =
"<?php echo $_SERVER['PHP_SELF']; ?>"
method="post">
Example: Approach 1
<html>
<body>
</body>
</html>
After clicking the submit button, the form data is sent for
processing to a PHP file named "welcome.php". The
form data is sent with the HTTP POST method.
welcome.php
<html> Using HTTP Post method
<body>
</body>
</html>
Using GET method
<html> welcome.php
<body> <html>
<body>
<form
action="welcome.php" Welcome <?php echo
method=get"> $_GET["name"]; ?><br>
Name: <input type="text" Your email address is:
name="name"><br> <?php echo
E-mail: <input type="text" $_GET["email"]; ?>
name="email"><br>
<input type="submit"> </body>
</form> </html>
</body>
</html>
GET vs. POST
Both GET and POST create an array (e.g. array( key => value,
key2 => value2, key3 => value3, ...)). This array holds key/value
pairs, where keys are the names of the form controls and
values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These
are superglobals,
$_GET is an array of variables passed to the current script via
the URL parameters.
$_POST is an array of variables passed to the current script via
the HTTP POST method.
When to use GET & POST
GET:
Information sent from a form with the GET method is visible
to everyone
GET also has limits on the amount of information to send. The
limitation is about 2000 characters.
It is possible to bookmark the page.
It may be used for sending non-sensitive data.
POST:
Information sent from a form with the POST method is
invisible to others.
no limits on the amount of information to send.
Developers prefer POST for sending form data.
Examples
Display content of $_POST
Display value of text input field
Display value of the hidden field
Display content of the text area
Display value(s) of (multiple) selection list
<?php
$name=$email=$website=$comment=$gender="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name=test_input($_POST["name"]);
$email=test_input($_POST["email"]);
$website=test_input($_POST["website"]);
$comment=test_input($_POST["comment"]);
$gender=test_input($_POST["gender"]);
}
function test_input($data){
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
?>
How to make required input
fields
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>
3 - Common operations
1. Check existence
Has a variable been set?
if (isset($_POST['myCheckbox2']))
echo "Option 2 was selected";
else
echo "Option 2 wasn't selected.";
2. Check which button was
pressed
Same as above
if (isset($_POST['button1']))
echo "Button 1 was pressed";
elseif (isset($_POST['button2']))
echo "Button 2 was pressed";
else
echo "no button pressed";
3. Email data
$to = "m.rutter@napier.ac.uk";
$subject = "form data";
$body = "Country chosen by the user:
$_POST['country1'] ";
mail($to,$subject,$body);
function showerror()
{
die("Error " . mysql_errno() . " : " . mysql_error());
}
if (!(mysql_select_db("winestor", $connection)))
showerror();
Example 1: Connect PHP script
to a database- exam_seq1.php
<?php
$servername = "localhost";
// Create connection
$conn = mysql_connect($servername,'root');
// Check connection
if (!$conn) {
die("Connection failed: " . mysql_connect_error());
}
echo "Connected successfully";
?>
Example 3:
<?php
$host="localhost";
$user="root";
$db="test";
$conn=mysql_connect($host,$user);
//$conn = mysql_connect($servername,'root');
// Check connection
if (!$conn) {
die("Connection failed: " . mysql_connect_error());
}
echo "Connected successfully";
Selection of the database
?>
<html>
<head>
</head>
<body>
<h1>PHP connect to MySQL</h1>
</body>
</html>
Building a Query
Directly
$query = 'select * from fruits';
Using input information
$winery = $_POST[fruits];
$query = select * from fruits where
winery=$apple;
Running a Query
mysql_query returns a result handle
$result = mysql_query($query, $connection)
mysql_num_rows indicates the number of rows returned
$num_rows = mysql_num_rows($result)
mysql_fetch_array creates array/hash of result
For ($n=0; $n<$num_rows;$n++)
$row = mysql_fetch_array($result)
Example 3:login
mysql_select_db($db);
if($count==1){
echo "you have successfully logged in";
exit();
}
else{
echo "invalid login info";
exit();}
}
?>
<!DOCTYPE html>
<html>
<body>
<form method="post" action="login_new.php">
Username: <input type="text" name="username" /><br /><br
/>
Password: <input type="password" name="password" /><br
/><br />
<input type="submit" name="submit" value="Login" />
</form>
</body>
</html>
Result of fetch_array
Contains both numeric and index tags
Values are duplicated
Example:
Query: select surname, city from customers;
Row: ( 0=>'Walker', surname=>'Walker', 1=>'Kent', 'city'=>'Kent'
);
Printing the Complete Row
By number
for ($i=0; $i<mysql_num_fields($result); $i++)
echo $row[$i] . " ";
By field
echo $row['surname'] . ' ' . $row['city'];
Example 4:exam_sql2.php
<?php
$error="<h1> Problem Connecting database</h1>";
$conn = mysql_connect('localhost','root');
mysql_select_db("test") or die("$error");
while($row=mysql_fetch_array($result)){
echo "<tr>";
echo
"<td>",$row['Id'],"</td><td>",$row['Name'],"</td><td>",$row['Email'],"</td>";
echo "</tr>";
}
output
Closing Database Connection
mysql_close() Closes database connection
$res=mysql_query($query);
Example 5:exam_sql3.php
<?php
echo "</table>";
mysql_close($conn);
?>
Inserting into a Database
SQL Query:
$res=mysql_query($query);
Example 6:exam_sql4.php
$conn = mysql_connect('localhost','root');
mysql_select_db("test") or die("$error");
$sql="INSERT INTO student(Id,Name,Email)
VALUES('3','AAA','aaa@gmail.com')";
$result=mysql_query($sql) or die("query failed: ".mysql_error());
$res=mysql_query($query);
Example 7: exam_sql5.php
$conn = mysql_connect('localhost','root');
mysql_select_db("test") or die("$error");