SlideShare ist ein Scribd-Unternehmen logo
1 von 110
Personal Home Page (Old)
Hypertext Preprocessor (Now)
By: @sami_Khan
What is PHP……?
PHP is a server scripting language, and a powerful tool
for making dynamic and interactive Web pages.
PHP is a widely-used, free, and efficient alternative to
competitors such as Microsoft's ASP.
XAMPP Server
Lecture#2
Download XAMPP: https://www.apachefriends.org/index.html
 Install XAMPP
 Start Apache Server and MySQL
 To Check that Apache server is running or not, we type
in Browser: http://localhost/
 XAMPP page should be opened
 Select language as English
XAMPP Home Page in English:
Notepad
Notepad++
Dreamweaver
Notepad
 Notepad is an Application in windows
 Path in Windows 8:
C:UsersManiAppDataRoamingMicrosoftWindowsStart
MenuProgramsAccessories
 Path in Windows 7
C:Windowssystem32
Start Menu:
Start > Programs > Accessories > Notepad
Notepad++
 Download Link:
https://notepad-plus-plus.org/download/v6.8.3.html
Notepad++
Adobe Dreamweaver
 Best Software for scripting
 Easy in use
PHP Syntax
Comment in PHP
Echo/Print
PHP Syntax
 Basic tags of PHP in which we type the whole code of
php.
Syntax:
<?php
// PHP code goes here
?>
PHP Coding
 During PHP coding we also need HTML, so normally we
use HTML & PHP together, (PHP in between HTML).
Comment in PHP
 In large programs we have to use ‘comments’, to
explain next code.
 In PHP we use
 // For One Whole Line
 # For One Whole Line
 /* For Multiple Lines
---
---
*/
Use of Comments in PHP
Echo/Print
 The echo/print function outputs one or more strings
 The echo function is slightly faster than print
Echo Syntax:
<?php
echo "Hello world!";
?>
Print Syntax:
<?php
print "Hello world!";
?>
echo “string”;
 String must be in double coats
 Semicolon ‘ ; ’ is used to end the line
PHP Code:
<?php
echo “I love Islam”;
?>
Rules for PHP variables:
 A variable defines with the $ (dollar sign)
 A variable name must start with a letter or the underscore
character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters
and underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive ($age and $Age are two
different variables)
Define a Variable
 Variable defines with ‘$’ (dollar sign):
$variable=value;
Example:
<?php
$txt = "Hello world!"; /* String Variable */
$x =35;
$y = 33.5;
?>
Note: When you assign a text value to a variable, put quotes around the value
Output Variables
 The PHP echo statement is often used to output data
to the screen.
 The following example will show how to output text
and a variable:
PHP Code:
<?php
$txt = “Islam";
echo "I love $txt";
?>
Scope of Variables
 In PHP, variables can be declared anywhere in the script.
 The scope of a variable is the part of the script where the
variable can be referenced/used.
 PHP has three different variable scopes:
 Global Variable: A variable declared outside a function has a GLOBAL SCOPE
and can only be accessed outside a function
 Local Variable: A variable declared within a function has a LOCAL SCOPE
and can only be accessed within that function
 Static Variable: when a function is completed/executed, its variables are
deleted. Sometimes we want a local variable.
We use the static keyword when you first declare the variable
static $x = 0;
PHP Data Types
Variables can store data of different types, and different
data types can do different things.
PHP supports the following data types:
 String
 Integer
 Float (floating point numbers - also called double)
 Boolean
 Array
String
 A string is a sequence of characters, like "Hello world!".
 A string can be any text inside quotes. You can use single or
double quotes:
Integer
An integer is a whole number (without decimals). It is a number
between -2,147,483,648 and +2,147,483,647.
Rules for integers:
 An integer must have at least one digit (0-9)
 An integer cannot contain comma or blanks
 An integer must not have a decimal point
 An integer can be either positive or negative
 Integers can be specified in three formats: decimal (10-based),
hexadecimal (16-based - prefixed with 0x) or octal (8-based -
prefixed with 0)
In the following example $x is an integer. The PHP var_dump()
function returns the data type and value:
Float
 A float (floating point number) is a number with a decimal
point or a number in exponential form.
 In the following example $x is a float. The PHP var_dump()
function returns the data type and value:
Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
Booleans are often used in conditional testing. You will
learn more about conditional testing in a later chapter of
this tutorial.
Array
 An array stores multiple values in one single variable.
 In the following example $cars is an array. The PHP var_dump()
function returns the data type and value:
PHP String Functions
 strlen() function returns the length of a string.
 str_word_count() function counts the number of words in a
string:
 strrev() function reverses a string:
 strpos() function searches for a specific text within a string.
The function returns the character position of the first match.
 str_replace() function replaces some characters with some
other characters in a string
PHP Constants
 To create a constant, use the define() function.
define(name, value, case-insensitive)
Parameters:
 name: Specifies the name of the constant
 value: Specifies the value of the constant
 case-insensitive: Specifies whether the constant name should be
case-insensitive. Default is false
<html>
<body>
<?php
// Constant name is case-sensitive by default(false)
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>
</body>
</html>
<html>
<body>
<?php
// constant name is case-sensitive by default(false)
define("GREETING", "Welcome to W3Schools.com!");
echo greeting;
?>
</body>
</html>
<html>
<body>
<?php
// Constant name is case-sensitive by default(false)
define("GREETING", "Welcome to W3Schools.com!“, true);
echo greeting;
?>
</body>
</html>
Constants are Global
 Constants are automatically global and can be used across the
entire script.
The example below uses a constant inside a function, but it is
defined outside the function:
<?php
define("GREETING", "Welcome to W3Schools.com!");
function myTest() {
echo GREETING;
}
myTest();
?>
PHP Operators
 Operators are used to perform operations on variables and
values.
PHP divides the operators in the following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators
Arithmetic Operators
 The PHP arithmetic operators are used with numeric values to
perform common arithmetical operations, such as addition,
subtraction, multiplication etc.
Assignment Operators
 The PHP assignment operators are used with numeric values
to write a value to a variable.
 The basic assignment operator in PHP is "=". It means that the
left operand gets set to the value of the assignment expression
on the right.
Comparison Operators
The PHP comparison operators are used to compare two values
(number or string):
Increment / Decrement Operators
 The PHP increment operators are used to increment a
variable's value.
 The PHP decrement operators are used to decrement a
variable's value.
Logical Operators
 The PHP logical operators are used to combine conditional
statements.
String Operators
 PHP has two operators that are specially designed for strings.
Array Operators
 The PHP array operators are used to compare arrays.
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:
 if statement - executes some code only if a specified condition is
true
 if...else statement - executes some code if a condition is true and
another code if the condition is false
 if...elseif....else statement - specifies a new condition to test, if the
first condition is false
 switch statement - selects one of many blocks of code to be
executed
The if Statement
The if statement is used to execute some code only if a
specified condition is true.
Syntax:
if (condition)
{
code to be executed if condition is true;
}
if statement:
<?php
$t = date("H");
if ($t < "20")
{
echo "Have a good day!";
}
?>
The if...else Statement
Use the if....else statement to execute some code if a condition
is true and another code if the condition is false.
Syntax:
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
The if...elseif....else Statement
Use the if....elseif...else statement to specify a new condition to
test, if the first condition is false.
Syntax:
if (condition) {
code to be executed if condition is true;
}
elseif (condition) {
code to be executed if condition is true;
}
else {
code to be executed if condition is false;
}
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;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
Note: Use break to prevent the code from running into the next case automatically.
PHP Loops
Instead of adding several almost equal code-lines in a script, we can
use loops to perform a task like this.
In PHP, we have the following looping statements:
 while - loops through a block of code as long as the specified
condition is true
 do...while - loops through a block of code once, and then repeats
the loop as long as the 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
While Loop
The while loop executes a block of code as long as the
specified condition is true.
Syntax:
while (condition is true)
{
code to be executed;
}
Do...While Loop
The Do...While loop will always execute the block of code once,
it will then check the condition, and repeat the loop while the
specified condition is true.
Syntax:
Do
{
code to be executed;
}
while (condition is true);
For Loop
The for loop is used when you know in advance how many times
the script should run.
Syntax:
for (init counter; test counter; increment counter)
{
code to be executed;
}
Parameters:
init counter: Initialize the loop counter value
test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop
continues. If it evaluates to FALSE, the loop ends.
increment counter: Increases the loop counter value
The example below displays the numbers from 0 to 10:
Foreach Loop
The foreach loop works only on arrays, and is used to loop
through each key/value pair in an array.
Syntax:
foreach ($array as $value)
{
code to be executed;
}
For every loop iteration, the value of the current array element is assigned
to $value and the array pointer is moved by one, until it reaches the last
array element.
The real power of PHP comes from its functions; it has
more than 1000 built-in functions.
Functions in PHP
 A function is a block of statements that can be used
repeatedly in a program.
 A function will not execute immediately when a page
loads.
 A function will be executed by a call to the function.
User Defined Function in PHP
A user defined function declaration starts with the word
"function":
Syntax:
function functionName()
{
code to be executed;
}
Note:
 A function name can start with a letter or underscore (not a number).
 Give the function a name that reflects what the function does!
 Function names are NOT case-sensitive.
// Calling a Function
// Creating a Function
Function Arguments
* Default Argument Values
Functions - Returning values
To let a function return a value, use the return statement:
<?php
function sum($x, $y)
{
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5,10) . "<br>";
echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);
?>
Some Built-in Functions in PHP
Rais-to-power and Square-root Function:
$a = 3; Results:
$b = 4;
$c = pow($a, 2) + pow($b, 2);
echo “ ’a’ rais to power 2 is ".pow($a, 2); 9
echo “ 'b' rais to power 2 is ".pow($b, 2); 16
echo "C = ".(pow($a, 2) + pow($b, 2)); 25
echo “ Square Root of C is ". sqrt($c); 5
A special kind of variable
Arrays
An array is a special variable, which can hold many values under a single
name, and you can access the values by referring to an index number.
Create an Array in PHP
In PHP, the array() function is used to create an array:
array();
In PHP, there are three types of arrays:
 Indexed arrays - Arrays with a numeric index
 Associative arrays - Arrays with named keys
 Multidimensional arrays - Arrays containing one or more arrays
Indexed Arrays
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0), like
this:
$cars = array("Volvo", "BMW", "Toyota");
Or the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Example
The following example creates an indexed array named $cars, assigns
three elements to it, and then prints a text containing the array values:
Get The Length of an Array
The count() Function:
The count() function is used to return the length (the
number of elements) of an array:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Loop Through an Indexed Array
To loop through and print all the values of an indexed array,
you could use a for loop, like this:
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
Associative Arrays
Associative arrays are arrays that use named keys that
you assign to them.
There are two ways to create an associative array:
Syntax:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Result: Peter is 35 years old.
Loop Through an Associative Array
To loop through and print all the values of an associative array,
you could use a foreach loop, like this:
Sort Functions For Arrays
The elements in an array can be sorted in alphabetical or
numerical order, descending or ascending.
PHP array sort functions:
 sort() - sort arrays in ascending order
 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order, according to the value
 ksort() - sort associative arrays in ascending order, according to the key
 arsort() - sort associative arrays in descending order, according to the value
 krsort() - sort associative arrays in descending order, according to the key
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
} Result: BMW
?> Toyota
Volvo
PHP Global Variables - Superglobals
Several predefined variables in PHP are "superglobals", which means
that they are always accessible, regardless of scope - and you can
access them from any function, class or file without having to do
anything special.
The PHP superglobal variables are:
 $GLOBALS
 $_SERVER
 $_REQUEST
 $_POST
 $_GET
 $_FILES
 $_ENV
 $_COOKIE
 $_SESSION
$GLOBALS
$GLOBALS is a PHP super global variable which is used to access global
variables from anywhere in the PHP script (also from within functions or
methods).
PHP stores all global variables in an array called $GLOBALS[index].
The index holds the name of the variable.
Example:
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition(); Result: 100
echo $z;
?>
$_SERVER
$_SERVER is a PHP super global variable which holds information
about headers, paths, and script locations.
The example below shows how to use some of the elements in
$_SERVER:
The following table lists the most important elements that can go inside $_SERVER:
$_REQUEST
PHP $_REQUEST is used to collect data after submitting an HTML form.
The example below shows a form with an input field and a submit
button. We point to this file itself for processing form data. Then, we can
use the super global variable $_REQUEST to collect the value of the
input field:
$_POST
PHP $_POST is widely used to collect form data after submitting an
HTML form with method="post". $_POST is also widely used to pass
variables.
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
$_GET
PHP $_GET can also be used to collect form data after submitting an
HTML form with method="get".
$_GET can also collect data sent in the URL.
Assume we have an HTML page that contains a hyperlink with
parameters:
<a href="test_get.php?subject=PHP&web=W3schools.com">Test $GET</a>
When a user clicks on the link "Test $GET", the parameters "subject" and
"web" is sent to "test_get.php", and you can then access their values in
"test_get.php" with $_GET.
PHP Form Handling
The PHP superglobals $_GET and $_POST are used to collect
form-data.
Simple HTML Form:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
welcome.php
When the user fills out the form above and clicks 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.
<html>
<body>
Welcome <?php echo $_POST["name"]; ?> <br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
GET vs. POST
Both GET and POST create an array [array( key => value, …)]. This
array holds key/value pairs, where keys are the names of the
form controls and values are the input data from the user.
 $_GET is an array of variables passed to the current script via the URL
parameters.
Information sent from a form with the GET method is visible to everyone.
 $_POST is an array of variables passed to the current script via the HTTP
POST method.
Information sent from a form with the POST method is invisible to others.
Note: Developers prefer POST for sending form data
Form Validation
Proper validation of form data is important to protect your form from
hackers and spammers!
The validation rules for the form above are as follows:
Form Element
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
 The $_SERVER["PHP_SELF"] sends the submitted form data to the page
itself, instead of jumping to a different page.
 The htmlspecialchars() function converts special characters to HTML
entities. This means that it will replace HTML characters like < and > with
&lt; and &gt;. This prevents attackers from exploiting the code by
injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.
PHP Forms - Validate E-mail and URL
Validate Name
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
Validate E-mail
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
If the URL address syntax is not valid, then store an error
message:
Validate URL
$website = test_input($_POST["website"]);
if (!preg_match("/b(?:(?:https?|ftp)://|www.)[-a-z0-
9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
•With PHP, you can connect to and manipulate databases.
•MySQL is the most popular database system used with PHP.
What is MySQL?
 MySQL is a database system used on the web
 MySQL is a database system that runs on a server
 MySQL is ideal for both small and large applications
 MySQL is very fast, reliable, and easy to use
 MySQL uses standard SQL
 MySQL compiles on a number of platforms
 MySQL is free to download and use
 MySQL is developed, distributed, and supported by Oracle
Corporation
 MySQL is named after co-founder Monty Widenius's daughter: My
MySQL Database
The data in a MySQL database are stored in tables. A table is a
collection of related data, and it consists of columns and rows.
Databases are useful for storing information categorically. A
company may have a database with the following tables:
 Employees
 Products
 Customers
 Orders
Note:
MySQL is the de-facto standard database system for web sites with
HUGE volumes of both data and end-users (like Facebook, Twitter, and
Wikipedia).
Database Queries
“A query is a question or a request.”
We can query a database for specific information and have a
recordset returned.
Look at the following query (using standard SQL):
SELECT LastName FROM Employees;
The query above selects all the data in the "LastName" column from
the "Employees" table.
Download MySQL Database
If you don't have a PHP server with a MySQL Database, you can
download it for free here: http://www.mysql.com
Look at http://www.mysql.com/customers for an overview of
companies using MySQL.
Php intro by sami kz

Weitere ähnliche Inhalte

Was ist angesagt? (20)

PHP
 PHP PHP
PHP
 
Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
P H P Part I, By Kian
P H P  Part  I,  By  KianP H P  Part  I,  By  Kian
P H P Part I, By Kian
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
 
Php web development
Php web developmentPhp web development
Php web development
 
Data types in php
Data types in phpData types in php
Data types in php
 
Php1
Php1Php1
Php1
 
PHP Comprehensive Overview
PHP Comprehensive OverviewPHP Comprehensive Overview
PHP Comprehensive Overview
 
03phpbldgblock
03phpbldgblock03phpbldgblock
03phpbldgblock
 
Ruby cheat sheet
Ruby cheat sheetRuby cheat sheet
Ruby cheat sheet
 
php basics
php basicsphp basics
php basics
 
Materi Dasar PHP
Materi Dasar PHPMateri Dasar PHP
Materi Dasar PHP
 
Php1
Php1Php1
Php1
 
Ruby quick ref
Ruby quick refRuby quick ref
Ruby quick ref
 
Cs3430 lecture 15
Cs3430 lecture 15Cs3430 lecture 15
Cs3430 lecture 15
 
Php
PhpPhp
Php
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Php Learning show
Php Learning showPhp Learning show
Php Learning show
 
Basic PHP
Basic PHPBasic PHP
Basic PHP
 

Ähnlich wie Php intro by sami kz

PHP MATERIAL
PHP MATERIALPHP MATERIAL
PHP MATERIALzatax
 
Php i-slides
Php i-slidesPhp i-slides
Php i-slidesAbu Bakar
 
Php i-slides (2) (1)
Php i-slides (2) (1)Php i-slides (2) (1)
Php i-slides (2) (1)ravi18011991
 
PHP - Introduction to PHP - Mazenet Solution
PHP - Introduction to PHP - Mazenet SolutionPHP - Introduction to PHP - Mazenet Solution
PHP - Introduction to PHP - Mazenet SolutionMazenetsolution
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPwahidullah mudaser
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQLArti Parab Academics
 
PHP Course (Basic to Advance)
PHP Course (Basic to Advance)PHP Course (Basic to Advance)
PHP Course (Basic to Advance)Coder Tech
 
1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_masterjeeva indra
 
Php by shivitomer
Php by shivitomerPhp by shivitomer
Php by shivitomerShivi Tomer
 

Ähnlich wie Php intro by sami kz (20)

PHP MATERIAL
PHP MATERIALPHP MATERIAL
PHP MATERIAL
 
Php
PhpPhp
Php
 
Php i-slides
Php i-slidesPhp i-slides
Php i-slides
 
Php i-slides
Php i-slidesPhp i-slides
Php i-slides
 
Php i-slides
Php i-slidesPhp i-slides
Php i-slides
 
Php i-slides (2) (1)
Php i-slides (2) (1)Php i-slides (2) (1)
Php i-slides (2) (1)
 
PHP Reviewer
PHP ReviewerPHP Reviewer
PHP Reviewer
 
php41.ppt
php41.pptphp41.ppt
php41.ppt
 
PHP InterLevel.ppt
PHP InterLevel.pptPHP InterLevel.ppt
PHP InterLevel.ppt
 
php-I-slides.ppt
php-I-slides.pptphp-I-slides.ppt
php-I-slides.ppt
 
PHP - Introduction to PHP - Mazenet Solution
PHP - Introduction to PHP - Mazenet SolutionPHP - Introduction to PHP - Mazenet Solution
PHP - Introduction to PHP - Mazenet Solution
 
unit 1.pptx
unit 1.pptxunit 1.pptx
unit 1.pptx
 
PHP - Web Development
PHP - Web DevelopmentPHP - Web Development
PHP - Web Development
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
PHP Course (Basic to Advance)
PHP Course (Basic to Advance)PHP Course (Basic to Advance)
PHP Course (Basic to Advance)
 
Php
PhpPhp
Php
 
1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master
 
PHP Basic & Variables
PHP Basic & VariablesPHP Basic & Variables
PHP Basic & Variables
 
Php by shivitomer
Php by shivitomerPhp by shivitomer
Php by shivitomer
 

Kürzlich hochgeladen

Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girlsRussian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girlsMonica Sydney
 
Best SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency DallasBest SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency DallasDigicorns Technologies
 
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge GraphsEleniIlkou
 
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdfMatthew Sinclair
 
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样ayvbos
 
Ballia Escorts Service Girl ^ 9332606886, WhatsApp Anytime Ballia
Ballia Escorts Service Girl ^ 9332606886, WhatsApp Anytime BalliaBallia Escorts Service Girl ^ 9332606886, WhatsApp Anytime Ballia
Ballia Escorts Service Girl ^ 9332606886, WhatsApp Anytime Balliameghakumariji156
 
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制pxcywzqs
 
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrStory Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrHenryBriggs2
 
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查ydyuyu
 
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查ydyuyu
 
Abu Dhabi Escorts Service 0508644382 Escorts in Abu Dhabi
Abu Dhabi Escorts Service 0508644382 Escorts in Abu DhabiAbu Dhabi Escorts Service 0508644382 Escorts in Abu Dhabi
Abu Dhabi Escorts Service 0508644382 Escorts in Abu DhabiMonica Sydney
 
Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...
Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...
Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...meghakumariji156
 
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdfpdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdfJOHNBEBONYAP1
 
Local Call Girls in Seoni 9332606886 HOT & SEXY Models beautiful and charmin...
Local Call Girls in Seoni  9332606886 HOT & SEXY Models beautiful and charmin...Local Call Girls in Seoni  9332606886 HOT & SEXY Models beautiful and charmin...
Local Call Girls in Seoni 9332606886 HOT & SEXY Models beautiful and charmin...kumargunjan9515
 
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdfMatthew Sinclair
 
Real Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtReal Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtrahman018755
 
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...APNIC
 
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdfMatthew Sinclair
 
Mira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
Mira Road Housewife Call Girls 07506202331, Nalasopara Call GirlsMira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
Mira Road Housewife Call Girls 07506202331, Nalasopara Call GirlsPriya Reddy
 
Call girls Service in Ajman 0505086370 Ajman call girls
Call girls Service in Ajman 0505086370 Ajman call girlsCall girls Service in Ajman 0505086370 Ajman call girls
Call girls Service in Ajman 0505086370 Ajman call girlsMonica Sydney
 

Kürzlich hochgeladen (20)

Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girlsRussian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
 
Best SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency DallasBest SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency Dallas
 
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
 
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
 
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
 
Ballia Escorts Service Girl ^ 9332606886, WhatsApp Anytime Ballia
Ballia Escorts Service Girl ^ 9332606886, WhatsApp Anytime BalliaBallia Escorts Service Girl ^ 9332606886, WhatsApp Anytime Ballia
Ballia Escorts Service Girl ^ 9332606886, WhatsApp Anytime Ballia
 
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
 
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrStory Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
 
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
 
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
 
Abu Dhabi Escorts Service 0508644382 Escorts in Abu Dhabi
Abu Dhabi Escorts Service 0508644382 Escorts in Abu DhabiAbu Dhabi Escorts Service 0508644382 Escorts in Abu Dhabi
Abu Dhabi Escorts Service 0508644382 Escorts in Abu Dhabi
 
Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...
Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...
Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...
 
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdfpdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
 
Local Call Girls in Seoni 9332606886 HOT & SEXY Models beautiful and charmin...
Local Call Girls in Seoni  9332606886 HOT & SEXY Models beautiful and charmin...Local Call Girls in Seoni  9332606886 HOT & SEXY Models beautiful and charmin...
Local Call Girls in Seoni 9332606886 HOT & SEXY Models beautiful and charmin...
 
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
 
Real Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtReal Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirt
 
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
 
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf
 
Mira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
Mira Road Housewife Call Girls 07506202331, Nalasopara Call GirlsMira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
Mira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
 
Call girls Service in Ajman 0505086370 Ajman call girls
Call girls Service in Ajman 0505086370 Ajman call girlsCall girls Service in Ajman 0505086370 Ajman call girls
Call girls Service in Ajman 0505086370 Ajman call girls
 

Php intro by sami kz

  • 1. Personal Home Page (Old) Hypertext Preprocessor (Now) By: @sami_Khan
  • 2. What is PHP……? PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 10.  Install XAMPP  Start Apache Server and MySQL
  • 11.  To Check that Apache server is running or not, we type in Browser: http://localhost/  XAMPP page should be opened  Select language as English
  • 12. XAMPP Home Page in English:
  • 14. Notepad  Notepad is an Application in windows  Path in Windows 8: C:UsersManiAppDataRoamingMicrosoftWindowsStart MenuProgramsAccessories  Path in Windows 7 C:Windowssystem32 Start Menu: Start > Programs > Accessories > Notepad
  • 17. Adobe Dreamweaver  Best Software for scripting  Easy in use
  • 18. PHP Syntax Comment in PHP Echo/Print
  • 19. PHP Syntax  Basic tags of PHP in which we type the whole code of php. Syntax: <?php // PHP code goes here ?>
  • 20. PHP Coding  During PHP coding we also need HTML, so normally we use HTML & PHP together, (PHP in between HTML).
  • 21. Comment in PHP  In large programs we have to use ‘comments’, to explain next code.  In PHP we use  // For One Whole Line  # For One Whole Line  /* For Multiple Lines --- --- */
  • 22. Use of Comments in PHP
  • 23. Echo/Print  The echo/print function outputs one or more strings  The echo function is slightly faster than print Echo Syntax: <?php echo "Hello world!"; ?> Print Syntax: <?php print "Hello world!"; ?>
  • 24. echo “string”;  String must be in double coats  Semicolon ‘ ; ’ is used to end the line PHP Code: <?php echo “I love Islam”; ?>
  • 25.
  • 26. Rules for PHP variables:  A variable defines with the $ (dollar sign)  A variable name must start with a letter or the underscore character  A variable name cannot start with a number  A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )  Variable names are case-sensitive ($age and $Age are two different variables)
  • 27. Define a Variable  Variable defines with ‘$’ (dollar sign): $variable=value; Example: <?php $txt = "Hello world!"; /* String Variable */ $x =35; $y = 33.5; ?> Note: When you assign a text value to a variable, put quotes around the value
  • 28. Output Variables  The PHP echo statement is often used to output data to the screen.  The following example will show how to output text and a variable: PHP Code: <?php $txt = “Islam"; echo "I love $txt"; ?>
  • 29. Scope of Variables  In PHP, variables can be declared anywhere in the script.  The scope of a variable is the part of the script where the variable can be referenced/used.  PHP has three different variable scopes:  Global Variable: A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function  Local Variable: A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function  Static Variable: when a function is completed/executed, its variables are deleted. Sometimes we want a local variable. We use the static keyword when you first declare the variable static $x = 0;
  • 30. PHP Data Types Variables can store data of different types, and different data types can do different things. PHP supports the following data types:  String  Integer  Float (floating point numbers - also called double)  Boolean  Array
  • 31. String  A string is a sequence of characters, like "Hello world!".  A string can be any text inside quotes. You can use single or double quotes:
  • 32. Integer An integer is a whole number (without decimals). It is a number between -2,147,483,648 and +2,147,483,647. Rules for integers:  An integer must have at least one digit (0-9)  An integer cannot contain comma or blanks  An integer must not have a decimal point  An integer can be either positive or negative  Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed with 0x) or octal (8-based - prefixed with 0)
  • 33. In the following example $x is an integer. The PHP var_dump() function returns the data type and value:
  • 34. Float  A float (floating point number) is a number with a decimal point or a number in exponential form.  In the following example $x is a float. The PHP var_dump() function returns the data type and value:
  • 35. Boolean A Boolean represents two possible states: TRUE or FALSE. $x = true; $y = false; Booleans are often used in conditional testing. You will learn more about conditional testing in a later chapter of this tutorial.
  • 36. Array  An array stores multiple values in one single variable.  In the following example $cars is an array. The PHP var_dump() function returns the data type and value:
  • 37. PHP String Functions  strlen() function returns the length of a string.  str_word_count() function counts the number of words in a string:  strrev() function reverses a string:  strpos() function searches for a specific text within a string. The function returns the character position of the first match.  str_replace() function replaces some characters with some other characters in a string
  • 38. PHP Constants  To create a constant, use the define() function. define(name, value, case-insensitive) Parameters:  name: Specifies the name of the constant  value: Specifies the value of the constant  case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false
  • 39. <html> <body> <?php // Constant name is case-sensitive by default(false) define("GREETING", "Welcome to W3Schools.com!"); echo GREETING; ?> </body> </html>
  • 40. <html> <body> <?php // constant name is case-sensitive by default(false) define("GREETING", "Welcome to W3Schools.com!"); echo greeting; ?> </body> </html>
  • 41. <html> <body> <?php // Constant name is case-sensitive by default(false) define("GREETING", "Welcome to W3Schools.com!“, true); echo greeting; ?> </body> </html>
  • 42. Constants are Global  Constants are automatically global and can be used across the entire script. The example below uses a constant inside a function, but it is defined outside the function: <?php define("GREETING", "Welcome to W3Schools.com!"); function myTest() { echo GREETING; } myTest(); ?>
  • 43.
  • 44. PHP Operators  Operators are used to perform operations on variables and values. PHP divides the operators in the following groups:  Arithmetic operators  Assignment operators  Comparison operators  Increment/Decrement operators  Logical operators  String operators  Array operators
  • 45. Arithmetic Operators  The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as addition, subtraction, multiplication etc.
  • 46. Assignment Operators  The PHP assignment operators are used with numeric values to write a value to a variable.  The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right.
  • 47. Comparison Operators The PHP comparison operators are used to compare two values (number or string):
  • 48. Increment / Decrement Operators  The PHP increment operators are used to increment a variable's value.  The PHP decrement operators are used to decrement a variable's value.
  • 49. Logical Operators  The PHP logical operators are used to combine conditional statements.
  • 50. String Operators  PHP has two operators that are specially designed for strings.
  • 51. Array Operators  The PHP array operators are used to compare arrays.
  • 52.
  • 53. 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:  if statement - executes some code only if a specified condition is true  if...else statement - executes some code if a condition is true and another code if the condition is false  if...elseif....else statement - specifies a new condition to test, if the first condition is false  switch statement - selects one of many blocks of code to be executed
  • 54. The if Statement The if statement is used to execute some code only if a specified condition is true. Syntax: if (condition) { code to be executed if condition is true; }
  • 55. if statement: <?php $t = date("H"); if ($t < "20") { echo "Have a good day!"; } ?>
  • 56. The if...else Statement Use the if....else statement to execute some code if a condition is true and another code if the condition is false. Syntax: if (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; }
  • 57. The if...elseif....else Statement Use the if....elseif...else statement to specify a new condition to test, if the first condition is false. Syntax: if (condition) { code to be executed if condition is true; } elseif (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; }
  • 58. 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; case label3: code to be executed if n=label3; break; ... default: code to be executed if n is different from all labels; } Note: Use break to prevent the code from running into the next case automatically.
  • 59.
  • 60. PHP Loops Instead of adding several almost equal code-lines in a script, we can use loops to perform a task like this. In PHP, we have the following looping statements:  while - loops through a block of code as long as the specified condition is true  do...while - loops through a block of code once, and then repeats the loop as long as the 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
  • 61. While Loop The while loop executes a block of code as long as the specified condition is true. Syntax: while (condition is true) { code to be executed; }
  • 62.
  • 63. Do...While Loop The Do...While loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true. Syntax: Do { code to be executed; } while (condition is true);
  • 64.
  • 65. For Loop The for loop is used when you know in advance how many times the script should run. Syntax: for (init counter; test counter; increment counter) { code to be executed; } Parameters: init counter: Initialize the loop counter value test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends. increment counter: Increases the loop counter value
  • 66. The example below displays the numbers from 0 to 10:
  • 67. Foreach Loop The foreach loop works only on arrays, and is used to loop through each key/value pair in an array. Syntax: foreach ($array as $value) { code to be executed; } For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.
  • 68.
  • 69. The real power of PHP comes from its functions; it has more than 1000 built-in functions.
  • 70. Functions in PHP  A function is a block of statements that can be used repeatedly in a program.  A function will not execute immediately when a page loads.  A function will be executed by a call to the function.
  • 71. User Defined Function in PHP A user defined function declaration starts with the word "function": Syntax: function functionName() { code to be executed; } Note:  A function name can start with a letter or underscore (not a number).  Give the function a name that reflects what the function does!  Function names are NOT case-sensitive.
  • 72. // Calling a Function // Creating a Function
  • 73. Function Arguments * Default Argument Values
  • 74. Functions - Returning values To let a function return a value, use the return statement: <?php function sum($x, $y) { $z = $x + $y; return $z; } echo "5 + 10 = " . sum(5,10) . "<br>"; echo "7 + 13 = " . sum(7,13) . "<br>"; echo "2 + 4 = " . sum(2,4); ?>
  • 75. Some Built-in Functions in PHP Rais-to-power and Square-root Function: $a = 3; Results: $b = 4; $c = pow($a, 2) + pow($b, 2); echo “ ’a’ rais to power 2 is ".pow($a, 2); 9 echo “ 'b' rais to power 2 is ".pow($b, 2); 16 echo "C = ".(pow($a, 2) + pow($b, 2)); 25 echo “ Square Root of C is ". sqrt($c); 5
  • 76. A special kind of variable
  • 77. Arrays An array is a special variable, which can hold many values under a single name, and you can access the values by referring to an index number.
  • 78. Create an Array in PHP In PHP, the array() function is used to create an array: array(); In PHP, there are three types of arrays:  Indexed arrays - Arrays with a numeric index  Associative arrays - Arrays with named keys  Multidimensional arrays - Arrays containing one or more arrays
  • 79. Indexed Arrays There are two ways to create indexed arrays: The index can be assigned automatically (index always starts at 0), like this: $cars = array("Volvo", "BMW", "Toyota"); Or the index can be assigned manually: $cars[0] = "Volvo"; $cars[1] = "BMW"; $cars[2] = "Toyota";
  • 80. Example The following example creates an indexed array named $cars, assigns three elements to it, and then prints a text containing the array values:
  • 81. Get The Length of an Array The count() Function: The count() function is used to return the length (the number of elements) of an array: <?php $cars = array("Volvo", "BMW", "Toyota"); echo count($cars); ?>
  • 82. Loop Through an Indexed Array To loop through and print all the values of an indexed array, you could use a for loop, like this: <?php $cars = array("Volvo", "BMW", "Toyota"); $arrlength = count($cars); for($x = 0; $x < $arrlength; $x++) { echo $cars[$x]; echo "<br>"; } ?>
  • 83. Associative Arrays Associative arrays are arrays that use named keys that you assign to them. There are two ways to create an associative array: Syntax: <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); echo "Peter is " . $age['Peter'] . " years old."; ?> Result: Peter is 35 years old.
  • 84. Loop Through an Associative Array To loop through and print all the values of an associative array, you could use a foreach loop, like this:
  • 85.
  • 86. Sort Functions For Arrays The elements in an array can be sorted in alphabetical or numerical order, descending or ascending. PHP array sort functions:  sort() - sort arrays in ascending order  rsort() - sort arrays in descending order  asort() - sort associative arrays in ascending order, according to the value  ksort() - sort associative arrays in ascending order, according to the key  arsort() - sort associative arrays in descending order, according to the value  krsort() - sort associative arrays in descending order, according to the key
  • 87. Example: <?php $cars = array("Volvo", "BMW", "Toyota"); sort($cars); $clength = count($cars); for($x = 0; $x < $clength; $x++) { echo $cars[$x]; echo "<br>"; } Result: BMW ?> Toyota Volvo
  • 88.
  • 89. PHP Global Variables - Superglobals Several predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special. The PHP superglobal variables are:  $GLOBALS  $_SERVER  $_REQUEST  $_POST  $_GET  $_FILES  $_ENV  $_COOKIE  $_SESSION
  • 90. $GLOBALS $GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. Example: <?php $x = 75; $y = 25; function addition() { $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; } addition(); Result: 100 echo $z; ?>
  • 91. $_SERVER $_SERVER is a PHP super global variable which holds information about headers, paths, and script locations. The example below shows how to use some of the elements in $_SERVER:
  • 92. The following table lists the most important elements that can go inside $_SERVER:
  • 93.
  • 94. $_REQUEST PHP $_REQUEST is used to collect data after submitting an HTML form. The example below shows a form with an input field and a submit button. We point to this file itself for processing form data. Then, we can use the super global variable $_REQUEST to collect the value of the input field:
  • 95. $_POST PHP $_POST is widely used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables. <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> Name: <input type="text" name="fname"> <input type="submit"> </form> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // collect value of input field $name = $_POST['fname']; if (empty($name)) { echo "Name is empty"; } else { echo $name; } } ?>
  • 96. $_GET PHP $_GET can also be used to collect form data after submitting an HTML form with method="get". $_GET can also collect data sent in the URL. Assume we have an HTML page that contains a hyperlink with parameters: <a href="test_get.php?subject=PHP&web=W3schools.com">Test $GET</a> When a user clicks on the link "Test $GET", the parameters "subject" and "web" is sent to "test_get.php", and you can then access their values in "test_get.php" with $_GET.
  • 97.
  • 98. PHP Form Handling The PHP superglobals $_GET and $_POST are used to collect form-data. Simple HTML Form: <html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="submit"> </form> </body> </html>
  • 99. welcome.php When the user fills out the form above and clicks 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. <html> <body> Welcome <?php echo $_POST["name"]; ?> <br> Your email address is: <?php echo $_POST["email"]; ?> </body> </html>
  • 100. GET vs. POST Both GET and POST create an array [array( key => value, …)]. This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.  $_GET is an array of variables passed to the current script via the URL parameters. Information sent from a form with the GET method is visible to everyone.  $_POST is an array of variables passed to the current script via the HTTP POST method. Information sent from a form with the POST method is invisible to others. Note: Developers prefer POST for sending form data
  • 101. Form Validation Proper validation of form data is important to protect your form from hackers and spammers! The validation rules for the form above are as follows:
  • 102. Form Element <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  The $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of jumping to a different page.  The htmlspecialchars() function converts special characters to HTML entities. This means that it will replace HTML characters like < and > with &lt; and &gt;. This prevents attackers from exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.
  • 103. PHP Forms - Validate E-mail and URL Validate Name $name = test_input($_POST["name"]); if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "Only letters and white space allowed"; } Validate E-mail $email = test_input($_POST["email"]); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; }
  • 104. If the URL address syntax is not valid, then store an error message: Validate URL $website = test_input($_POST["website"]); if (!preg_match("/b(?:(?:https?|ftp)://|www.)[-a-z0- 9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|]/i",$website)) { $websiteErr = "Invalid URL"; }
  • 105. •With PHP, you can connect to and manipulate databases. •MySQL is the most popular database system used with PHP.
  • 106. What is MySQL?  MySQL is a database system used on the web  MySQL is a database system that runs on a server  MySQL is ideal for both small and large applications  MySQL is very fast, reliable, and easy to use  MySQL uses standard SQL  MySQL compiles on a number of platforms  MySQL is free to download and use  MySQL is developed, distributed, and supported by Oracle Corporation  MySQL is named after co-founder Monty Widenius's daughter: My
  • 107. MySQL Database The data in a MySQL database are stored in tables. A table is a collection of related data, and it consists of columns and rows. Databases are useful for storing information categorically. A company may have a database with the following tables:  Employees  Products  Customers  Orders Note: MySQL is the de-facto standard database system for web sites with HUGE volumes of both data and end-users (like Facebook, Twitter, and Wikipedia).
  • 108. Database Queries “A query is a question or a request.” We can query a database for specific information and have a recordset returned. Look at the following query (using standard SQL): SELECT LastName FROM Employees; The query above selects all the data in the "LastName" column from the "Employees" table.
  • 109. Download MySQL Database If you don't have a PHP server with a MySQL Database, you can download it for free here: http://www.mysql.com Look at http://www.mysql.com/customers for an overview of companies using MySQL.