- PHP 5 Introduction
- PHP 5 Installation
- PHP 5 Syntax
- PHP 5 Variables
- PHP 5 echo and print Statements
- PHP 5 Data Types
- PHP 5 Strings
- PHP 5 Constants
- PHP 5 Operators
- PHP 5 switch Statement
- PHP 5 while Loops
- PHP 5 for Loops
- PHP 5 Functions
- PHP 5 Arrays
- PHP 5 Sorting Arrays
- PHP 5 Global Variables – Superglobals
- PHP 5 Form Handling
- PHP 5 Form Validation
- PHP 5 Forms - Required Fields
- PHP 5 Forms - Validate E-mail and URL
- PHP 5 Complete Form Example
- PHP 5 Multidimensional Arrays
- PHP 5 Date and Time
- PHP 5 Include Files
- PHP 5 File Handling
- PHP 5 File Open/Read/Close
- PHP 5 File Create/Write
- PHP 5 File Upload
- PHP 5 Cookies
- PHP 5 Sessions
- PHP Filters
- PHP Filters Advanced
- PHP Error Handling
- PHP Exception Handling
- PHP MySQL Database
- PHP Connect to MySQL
- PHP Create a MySQL Database
- PHP Create MySQL Tables
- PHP Insert Data Into MySQL
- PHP Get ID of Last Inserted Record
- PHP Insert Multiple Records
- PHP Prepared Statements
- PHP Select Data From MySQL
- PHP Delete Data From MySQL
- PHP Update Data in MySQL
- PHP Limit Data Selections From MySQL
- PHP XML Parsers
- PHP Simple XML Parser
- PHP SimpleXML - Get Node/Attribute Values
- PHP XML Expat Parser
- PHP XML DOM Parser
- AJAX Introduction
- PHP - AJAX and PHP
- PHP - AJAX and MySQL
- PHP Example - AJAX and XML
- PHP Example - AJAX Live Search
- PHP Example - AJAX RSS Reader
- PHP Example - AJAX Poll
- What We have done?
Sunday, May 6, 2018
Friday, May 4, 2018
What We have done ?

What
We have done ?
PHP
Syntax
Write text
to the output using PHP
Add comments
in PHP
Keywords,
classes, functions, and user-defined functions ARE NOT case-sensitive
Variable
names ARE case-sensitive
Examples
explained
PHP
Variables
Create
different variables
Test global
scope (variable outside function)
Test local
scope (variable inside function)
Use the
global keyword to access a global variable from within a function
Use the
$GLOBALS[] array to access a global variable from within a function
Use the
static keyword to let a local variable not be deleted after execution of
function
Examples
explained
PHP
Echo and Print
Display
strings with the echo command
Display
strings and variables with the echo command
Display
strings with the print command
Display
strings and variables with the print command
Examples
explained
PHP
Data Types
PHP string
PHP integer
PHP float
PHP array
PHP object
PHP NULL
value
Examples
explained
PHP
Strings
Get the
length of a string - strlen()
Count the
number of words in a string - str_word_count()
Reverse a
string - strrev()
Search for a
specific text within a string - strpos()
Replace text
within a string - str_replace()
Examples
explained
PHP
Constants
Case-sensitive
constant name
Case-insensitive
constant name
Examples
explained
PHP
Operators
Arithmetic
operator: Addition (+)
Arithmetic
operator: Subtraction (-)
Arithmetic
operator: Multiplication (*)
Arithmetic
operator: Division (/)
Arithmetic
operator: Modulus (%)
Assignment operator:
x = y
Assignment
operator: x += y
Assignment
operator: x -= y
Assignment
operator: x *= y
Assignment
operator: x /= y
Assignment
operator: x %= y
Comparison
operator: Equal (==)
Comparison
operator: Identical (===)
Comparison
operator: Not equal (!=)
Comparison
operator: Not equal (<>)
Comparison
operator: Not identical (!==)
Comparison
operator: Greater than (>)
Comparison
operator: Less than (<)
Comparison
operator: Greater than or equal (>=)
Comparison
operator: Less than or equal (<=)
Increment
operator: ++$x
Increment
operator: $x++
Decrement
operator: --$x
Decrement
operator: $x--
Logical
operator: and
Logical
operator: or
Logical
operator: xor
Logical
operator: && (and)
Logical
operator: || (or)
Logical
operator: not
String
operator: Concatenation of $txt1 and $txt2
String
operator: Appends $txt2 to $txt1
Array
operator: Union (+)
Array
operator: Equality (==)
Array
operator: Identity (===)
Array
operator: Inequality (!=)
Array
operator: Inequality (<>)
Array
operator: Non-identity (!==)
Examples
explained
PHP
If...Else and Switch Statements
The if
statement
The
if...else statement
The
if...elseif...else statement
The switch
statement
Examples
explained
PHP
While and For Loops
The while
loop
The
do...while loop
Another
do...while loop
The for loop
The foreach
loop
Examples
explained
PHP
Functions
Create a
function
Function
with one argument
Function
with two arguments
Function
with default argument value
Function
that returns a value
Examples
explained
PHP
Arrays
Indexed arrays
count() -
Return the length of an array
Loop through
an indexed array
Associative
arrays
Loop through
an associative array
Examples
explained
PHP
Sorting Arrays
sort() -
Sort array in ascending alphabetical order
sort() -
Sort array in ascending numerical order
rsort() -
Sort array in descending alphabetical order
rsort() -
Sort array in descending numerical order
asort() -
Sort array in ascending order, according to value
ksort() -
Sort array in ascending order, according to key
arsort() -
Sort array in descending order, according to value
krsort() -
Sort array in descending order, according to key
Examples
explained
PHP
Superglobals
$GLOBAL -
Used to access global variables from anywhere in the PHP script
$_SERVER -
Holds information about headers, paths, and script locations
$_REQUEST -
Used to collect data after submitting an HTML form
$_POST -
Used to collect form data after submitting an HTML form. Also used to pass
variables
$_GET -
Collect data sent in the URL
Examples
explained
PHP
Form Validation
PHP Form
Validation
Example
explained
PHP
Multidimensional Arrays
Output
elements from a multidimensional array
Loop through
a multidimensional array
Examples
explained
PHP
Date and Time
Format
today's date in several ways
Automatically
update the copyright year on your website
Output the
current time (server time)
Set
timezone, then output current time
Create a
date and time from a number of parameters in mktime()
Create a
date and time from the strtotime() function
Create more
dates/times from strtotime()
Output the
dates for the next six Saturdays
Output the
number of days until 4th of July
Examples
explained
PHP
Include Files
Use include
to include "footer.php" in a page
Use include
to include "menu.php" in a page
Use include
to include "vars.php" in a page
Use include
to include a non-existing file
Use require
to include a non-existing file
Examples
explained
PHP
File Handling
Use
readfile() to read a file and write it to the output buffer
Examples
explained
PHP
File Open/Read/Close
Use fopen(),
fread(), and fclose() to open, read, and close a file
Use fgets()
to read a single line from a file
Use feof()
to read through a file, line by line, until end-of-file is reached
Use fgetc()
to read a single character from a file
Examples
explained
PHP
Cookies
Create and
retrieve a cookie
Modify a
cookie value
Delete a
cookie
Check if
cookies are enabled
Examples
explained
PHP
Sessions
Start a
session
Get session
variable values
Get all
session variable values
Modify a
session variable
Destroy a
session
Examples
explained
PHP
Filters
Use
filter_list() to list what the PHP filter extension offers
Sanitize a
string
Validate an
integer
Validate an
integer that is 0
Validate an
IP address
Sanitize and
validate an email address
Sanitize and
validate a URL
Examples
explained
PHP
Select Data From MySQL
Select data
with MySQLi (Object-oriented)
Select data
with MySQLi (Object-oriented) and put result in an HTML table
Select data
with MySQLi (Procedural)
Select data
with PDO (+ Prepared statements)
Examples
explained
PHP
SimpleXML Parser
Use
simplexml_load_string() to read XML data from a string
Use
simplexml_load_file() to read XML data from a file
Get node
values
Get node
values of specific elements
Get node
values - loop
Get
attribute values
Get
attribute values - loop
Examples
explained
PHP
XML Expat Parser
Initialize
an XML Expat parser, define some handlers, then parse an XML file
Examples
explained
PHP Example - AJAX Poll

PHP
Example - AJAX Poll
AJAX Poll
The
following example will demonstrate a poll where the result is shown without
reloading.
Do you like
PHP and AJAX so far?
Yes:
No:
Example
Explained - The HTML Page
When a user
chooses an option above, a function called "getVote()" is executed.
The function is triggered by the "onclick" event:
<html>
<head>
<script>
function
getVote(int) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera,
Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new
ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 &&
this.status==200) {
document.getElementById("poll").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","poll_vote.php?vote="+int,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div
id="poll">
<h3>Do
you like PHP and AJAX so far?</h3>
<form>
Yes:
<input
type="radio" name="vote" value="0"
onclick="getVote(this.value)">
<br>No:
<input
type="radio" name="vote" value="1"
onclick="getVote(this.value)">
</form>
</div>
</body>
</html>
The
getVote() function does the following:
Create an
XMLHttpRequest object
Create the
function to be executed when the server response is ready
Send the
request off to a file on the server
Notice that
a parameter (vote) is added to the URL (with the value of the yes or no option)
The PHP File
The page on
the server called by the JavaScript above is a PHP file called
"poll_vote.php":
<?php
$vote
= $_REQUEST['vote'];
//get
content of textfile
$filename
= "poll_result.txt";
$content
= file($filename);
//put
content in array
$array
= explode("||", $content[0]);
$yes
= $array[0];
$no
= $array[1];
if
($vote == 0) {
$yes = $yes + 1;
}
if
($vote == 1) {
$no = $no + 1;
}
//insert
votes to txt file
$insertvote
= $yes."||".$no;
$fp
= fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>
<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<img
src="poll.gif"
width='<?php
echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php
echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>
<img
src="poll.gif"
width='<?php
echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php
echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
</table>
The value is
sent from the JavaScript, and the following happens:
Get the
content of the "poll_result.txt" file
Put the
content of the file in variables and add one to the selected variable
Write the
result to the "poll_result.txt" file
Output a
graphical representation of the poll result
The Text
File
The text
file (poll_result.txt) is where we store the data from the poll.
It is stored
like this:
0||0
The first
number represents the "Yes" votes, the second number represents the
"No" votes.
Note: Remember
to allow your web server to edit the text file. Do NOT give everyone access,
just the web server (PHP).
PHP Example - AJAX RSS Reader

PHP
Example - AJAX RSS Reader
An RSS
Reader is used to read RSS Feeds.
AJAX
RSS Reader
The
following example will demonstrate an RSS reader, where the RSS-feed is loaded
into a webpage without reloading:
RSS-feed
will be listed here...
Example Explained
- The HTML Page
When a user
selects an RSS-feed in the dropdown list above, a function called
"showRSS()" is executed. The function is triggered by the
"onchange" event:
<html>
<head>
<script>
function
showRSS(str) {
if (str.length==0) {
document.getElementById("rssOutput").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera,
Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 &&
this.status==200) {
document.getElementById("rssOutput").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getrss.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select
onchange="showRSS(this.value)">
<option
value="">Select an RSS-feed:</option>
<option
value="Google">Google News</option>
<option
value="NBC">NBC News</option>
</select>
</form>
<br>
<div
id="rssOutput">RSS-feed will be listed here...</div>
</body>
</html>
The
showRSS() function does the following:
Check if an
RSS-feed is selected
Create an
XMLHttpRequest object
Create the
function to be executed when the server response is ready
Send the
request off to a file on the server
Notice that
a parameter (q) is added to the URL (with the content of the dropdown list)
The PHP File
The page on
the server called by the JavaScript above is a PHP file called
"getrss.php":
<?php
//get
the q parameter from URL
$q=$_GET["q"];
//find
out which feed was selected
if($q=="Google")
{
$xml=("http://news.google.com/news?ned=us&topic=h&output=rss");
}
elseif($q=="NBC") {
$xml=("http://rss.msnbc.msn.com/id/3032091/device/rss/rss.xml");
}
$xmlDoc
= new DOMDocument();
$xmlDoc->load($xml);
//get
elements from "<channel>"
$channel=$xmlDoc->getElementsByTagName('channel')->item(0);
$channel_title
= $channel->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$channel_link
= $channel->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc
= $channel->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
//output
elements from "<channel>"
echo("<p><a
href='" . $channel_link
. "'>" . $channel_title .
"</a>");
echo("<br>");
echo($channel_desc
. "</p>");
//get
and output "<item>" elements
$x=$xmlDoc->getElementsByTagName('item');
for
($i=0; $i<=2; $i++) {
$item_title=$x->item($i)->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$item_link=$x->item($i)->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$item_desc=$x->item($i)->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
echo ("<p><a href='" .
$item_link
. "'>" . $item_title .
"</a>");
echo ("<br>");
echo ($item_desc . "</p>");
}
?>
When a
request for an RSS feed is sent from the JavaScript, the following happens:
Check which
feed was selected
Create a new
XML DOM object
Load the RSS
document in the xml variable
Extract and
output elements from the channel element
Extract and
output elements from the item elements
PHP Example - AJAX Live Search
PHP
Example - AJAX Live Search
AJAX can be
used to create more user-friendly and interactive searches.
AJAX Live
Search
The
following example will demonstrate a live search, where you get search results
while you type.
Live search
has many benefits compared to traditional searching:
Results are
shown as you type
Results
narrow as you continue typing
If results
become too narrow, remove characters to see a broader result
Search for a
Omega page in the input field below:
The results
in the example above are found in an XML file (links.xml). To make this example
small and simple, only six results are available.
Example
Explained - The HTML
Page
When a user
types a character in the input field above, the function
"showResult()" is executed. The function is triggered by the
"onkeyup" event:
<html>
<head>
<script>
function
showResult(str) {
if (str.length==0) {
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera,
Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new
ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 &&
this.status==200) {
document.getElementById("livesearch").innerHTML=this.responseText;
document.getElementById("livesearch").style.border="1px
solid #A5ACB2";
}
}
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<input
type="text" size="30"
onkeyup="showResult(this.value)">
<div
id="livesearch"></div>
</form>
</body>
</html>
Source code
explanation:
If the input
field is empty (str.length==0), the function clears the content of the
livesearch placeholder and exits the function.
If the input
field is not empty, the showResult() function executes the following:
Create an
XMLHttpRequest object
Create the
function to be executed when the server response is ready
Send the
request off to a file on the server
Notice that
a parameter (q) is added to the URL (with the content of the input field)
The PHP File
The page on
the server called by the JavaScript above is a PHP file called
"livesearch.php".
The source
code in "livesearch.php" searches an XML file for titles matching the
search string and returns the result:
<?php
$xmlDoc=new
DOMDocument();
$xmlDoc->load("links.xml");
$x=$xmlDoc->getElementsByTagName('link');
//get
the q parameter from URL
$q=$_GET["q"];
//lookup
all links from the xml file if length of q>0
if
(strlen($q)>0) {
$hint="";
for($i=0; $i<($x->length); $i++) {
$y=$x->item($i)->getElementsByTagName('title');
$z=$x->item($i)->getElementsByTagName('url');
if ($y->item(0)->nodeType==1) {
//find a link matching the search text
if
(stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) {
if ($hint=="") {
$hint="<a href='" .
$z->item(0)->childNodes->item(0)->nodeValue .
"' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue .
"</a>";
} else {
$hint=$hint . "<br /><a
href='" .
$z->item(0)->childNodes->item(0)->nodeValue .
"' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue
. "</a>";
}
}
}
}
}
//
Set output to "no suggestion" if no hint was found
//
or to the correct values
if
($hint=="") {
$response="no suggestion";
}
else {
$response=$hint;
}
//output
the response
echo
$response;
?>
If there is
any text sent from the JavaScript (strlen($q) > 0), the following happens:
Load an XML
file into a new XML DOM object
Loop through
all <title> elements to find matches from the text sent from the
JavaScript
Sets the
correct url and title in the "$response" variable. If more than one
match is found, all matches are added to the variable
If no
matches are found, the $response variable is set to "no suggestion"