You are on page 1of 30

PHP/MySQL

PHP Introduction

PHP is entirely server-side. When a PHP script executes, it doesn’t interact directly
with the browser. The final product which is usually HTML document is dealt with the
by the requesting browser. PHP can be embedded directly into HTML.

Here’s a quick example of the popular Hello World program in PHP:

<html>
<head>
<title>Hello, World!</title>
<head>
<body>
<?php print(“Hello, World!\n”); ?>
</body>
</html>

• PHP can be used to write GUI applications.


• Interfaces to several databases
• Underlying Zend engine provides API for developing custom extensions (.dll for
Windows and .so for Unix).

PHP History

PHP succeeds an older product, named PHP/FI. PHP/FI was created by Rasmus
Lerdorf in 1995, initially as a simple set of Perl scripts for tracking accesses to his
online resume. He named this set of scripts 'Personal Home Page Tools'.
PHP 3.0 was the first version that closely resembles PHP as we know it today. It was
created by Andi Gutmans and Zeev Suraski in 1997.
By the winter of 1998, shortly after PHP 3.0 was officially released, Andi Gutmans
and Zeev Suraski had begun working on a rewrite of PHP's core. The design goals
were to improve performance of complex applications, and improve the modularity of
PHP's code base.
The new engine, dubbed 'Zend Engine' (comprised of their first names, Zeev and
Andi), met these design goals successfully, and was first introduced in mid 1999
Variables
PHP is a weakly typed language. In PHP, we can make the variable $I anything at
any time. PHP allows keywords to be used as variable names though it is not a
good practice.
PHP supports the following data types:

Scalar Data Types

Scalar Boolean, integer, floating-point (double), string


Compound Array, object
Special Resource, null

Boolean example:

$display_item = true;
if ($display_table == true)
{
do_something();
}

Integer example

$int_max = 2147483647;
Integers cannot contain any numbers with decimal points. If the number has any
digits on the right side of the decimal point, it is considered a Floating Point value.

If a PHP variable is assigned the value 1, then it is considered an integer internally.


If the variable is assigned True or False, then the variable is considered a Boolean.
The behavior of integers and their internal data type representation can be verified
with the var_dump() function.

$int1 = 1;
echo(var_dump($int1) . “,br>”);

FP example

$myfloat = 1e12;
$myfloat = 1000000000000.00;

Floating point numbers allow for much greater precision than integers. The exact
precision and size of the variable allowed depends on the platform PHP is used on.
Generally, FP number accuracy is 14 decimal places. Max size is 1.8 x 10308
(defined by IEEE 64-bit standard).

String

$string1 = ‘This is a string with \’Single Quotes\’’;


(use \ to escape the quotes)

To print single quotes, inside a string


$string2 = “This string has ‘Single Quotes’ inside a double quotes”;

Another way of defining a string is by using the heredoc syntax.

$string3 = <<heredoc_identifier
“This paragraph is written using heredoc id.
heredoc helps in avoiding using “ for beginning
a string. any special characters or quotes can
be used in this para.”
heredoc_identifier;
Print($string3);

PHP does not impose any size limitations on strings. PHP dynamically allocates
memory for a string as the string grows.

String literals defined with double quotes understand the following escape
characters:

Escape Character Represented


Sequence
\n Linefeed
\r Carriage Return
\t Tab
\\ Backslash
\$ Dollar Sign
\” Double Quote

There are 2 syntaxes for handling variables in a string.

$bike = “Pulsar”;
$string1 = “$bikes are the best”;

The above $string1 variable errors out indicating that $bikes is not a valid variable.
So if you want to assign “Pulsars are the best” to a string variable, then you need to
do the following:

$string1 = “${bikes]s are the best”;

The above usage of ${bike} will work fine.

Complex Data Types

Arrays

$array1 = array();
$array1[0] = “Pulsar”;
$array1[1] = “Activa”;
$array1[2] = “Deo”;
$array1[3] = “Honda”;

Each item in the array can be printed as follows:


foreach ($array1 as $bike)
{ print(“${bike}s are maintenance-free; }

PHP arrays can also be used as Associative arrays as seen in the following example.

$bikes = array
(
“Honda” => array(“Kinetic”, Honda”),
“Bajaj” => array(“Pulsar”, “Vespa”)
);

Objects

Objects are instantiation of classes. An object encapsulates the properties and


interactions into one package.

Special Data Types

Resource

Resources are special data types needed by several functions within PHP and are
allocated by the programmer. But the deallocation of resources will be handled by
PHP. Manual deallocation will also be available. Resources are created and used by
special functions

<?php

$ftp_server = "ftp.example.com";

// set up a connection or die


$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to
$ftp_server");

?>

Null

A null value means no value is set for the variable. The keyword Null is not case
sensitive.

A variable is considered to be NULL if


• it has been assigned the constant NULL.
• it has not been set to any value yet.
• it has been unset().

<?php
$var = NULL;
?>

Pseudo Datatypes
Constants
define(“READ”, 1);
define(“SAVE”,2);
define(“DELETE”,3)
print(DELETE);
$constant_name = “READ”;

Typecasting

To change a variable’s datatype, you need to use the settype function.

$int1 = 200;
var_dump($int1);
print(“<br>”);
settype($int1,”double”):
var_dump($int1);
print(“<br>”);

Casr Cast To
(array) Array
(bool),(Boolean) Boolean
(real),(double), (float) Float
(int),(integer) Integer
(object) Object
(string) String

<?php
$result = “70 is not the result” + 30;
print(“The result is ….”);
var_dump($result);
?>

Array conversion example:

<?php
$scalar1 = 70;
$array1 = (array)$scalar1;
var_dump($array1);
?>

Variable Scope

The scope of a variable is the context within which it is defined. For the most part all
PHP variables only have a single scope. This single scope spans included and
required files as well. For example
<?php
$a = 1;
include 'b.inc';
?>
The following script will not produce any output because the echo statement refers to
a local version of the $a variable, and it has not been assigned a value within this
scope.
<?php
$a = 1; /* global scope */

function Test()
{
echo $a; /* reference to local scope variable */
}

Test();
?>

In PHP global variables must be declared global inside a function if they are going to
be used in that function

<?php
$a = 1;
$b = 2;

function Sum()
{
global $a, $b;

$b = $a + $b;
}

Sum();
echo $b;
?>

A second way to access variables from the global scope is to use the special PHP-
defined $GLOBALS array. The previous example can be rewritten as:

<?php
$a = 1;
$b = 2;

function Sum()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}

Sum();
echo $b;
?>

The $GLOBALS array is an associative array with the name of the global variable
being the key and the contents of that variable being the value of the array element.
Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a
superglobal.
Here's an example demonstrating the power of superglobals:

<?php
function test_global()
{
// Most predefined variables aren't "super" and require
// 'global' to be available to the functions local scope.
global $HTTP_POST_VARS;
echo $HTTP_POST_VARS['name'];
// Superglobals are available in any scope and do
// not require 'global'. Superglobals are available
// as of PHP 4.1.0, and HTTP_POST_VARS is now
// deemed deprecated.
echo $_POST['name'];
}
?>

From version 4.1.0 onward, PHP provides an additional set of predefined arrays
containing variables from the web server (if applicable), the environment, and user
input. These new arrays are rather special in that they are automatically global--i.e.,
automatically available in every scope. For this reason, they are often known as
'autoglobals' or 'superglobals'. (There is no mechanism in PHP for user-defined
superglobals.) The superglobals are listed below. Also, you'll notice how the older
predefined variables ($HTTP_*_VARS) still exist. As of PHP 5.0.0, the long PHP
predefined variable arrays may be disabled with the register_long_arrays directive.

PHP Superglobals

$GLOBALS
Contains a reference to every variable which is currently available within the global
scope of the script. The keys of this array are the names of the global variables.
$GLOBALS has existed since PHP 3.

$_SERVER
Variables set by the web server or otherwise directly related to the execution
environment of the current script. Analogous to the old $HTTP_SERVER_VARS array
(which is still available, but deprecated).

$_GET
Variables provided to the script via URL query string. Analogous to the old
$HTTP_GET_VARS array (which is still available, but deprecated).

$_POST
Variables provided to the script via HTTP POST. Analogous to the old
$HTTP_POST_VARS array (which is still available, but deprecated).

$_COOKIE
Variables provided to the script via HTTP cookies. Analogous to the old
$HTTP_COOKIE_VARS array (which is still available, but deprecated).

$_FILES
Variables provided to the script via HTTP post file uploads. Analogous to the old
$HTTP_POST_FILES array (which is still available, but deprecated).
$_ENV
Variables provided to the script via the environment. Analogous to the old
$HTTP_ENV_VARS array (which is still available, but deprecated).

$_REQUEST
Variables provided to the script via the GET, POST, and COOKIE input mechanisms,
and which therefore cannot be trusted..
Note: When running on the command line , this will not include the argv and
argc entries; these are present in the $_SERVER array.

$_SESSION
Variables which are currently registered to a script's session. Analogous to the old
$HTTP_SESSION_VARS array (which is still available, but deprecated)..

Variable Variables

Normal variable setting is as follows:

<?php
$a = 'hello';
?>
A variable variable takes the value of a variable and treats that as the name of a
variable. In the above example, hello, can be used as the name of a variable by
using two dollar signs. i.e.

<?php
$$a = 'world';
?>
At this point two variables have been defined and stored in the PHP symbol tree: $a
with contents "hello" and $hello with contents "world". Therefore, this statement:

<?php
echo "$a ${$a}";
?>

produces the exact same output as:

<?php
echo "$a
$hello";
?>

.i.e. they both produce: hello world


Operators & Expressions
Arithmetic Operators

Operation Operator Example


Multiplication * $a * $b
Division / $a / $b
Modulus % $a % $b
Addition + $a + $b
Subtraction - $a - $b

Relational Operators

Operation Operator Example


Less Than < $a < $b
Less than or equal to <= $a <= $b
Greater than > $a > $b
Greater than or equal to >= $a >= $b

Equality Operators

Operation Operator Example


Equality == $a == $b
Inequality != $a != $b
Inequality <> $a ===$b
Identity === $a !==$b
Nonidentity !==

Logical Operators

Operation Operator Class Associativity Example


Logical AND && Binary Left $a && $b
Logical OR || Binary Left $a || $b
Logical NOT ! Unary Right !$a
Logical XOR xor Binary Left $a xor $b
Logical AND and Binary Left $a and $b
Logical OR or Binary Left $a or $b
Operator Precedence

Additional
Associativity Operators
Information
non-associative new new
left [ array()
non-associative ++ -- increment/decrement
non-associative ! ~ - (int) (float) (string) (array) (object) @ types
left */% arithmetic
left +-. arithmetic and string
left << >> bitwise
non-associative < <= > >= comparison
non-associative == != === !== comparison
left & bitwise and references
left ^ bitwise
left | bitwise
left && logical
left || logical
left ?: ternary
right = += -= *= /= .= %= &= |= ^= <<= >>= assignment
left and logical
left xor logical
left or logical
left , many uses

Associativity
<?php
$a = 3 * 3 % 5; // (3 * 3) % 5 = 4
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2

$a = 1;
$b = 2;
$a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5
?>

Use parentheses to increase readability of the code.

Bitwise Operator

Operation Operator Class Associativity Example


Bitwise AND & Binary Left $a & $b
Bitwise inclusive OR | Binary Left $a | $b
Bitwise XOR ^ Binary Left $a ^ $b
Bitwise NOT ~ Unary Right ~$a
Bitwise left-shift << Binary Left $a << $b
Bitwise right-shift >> Binary Left $a >> $b
<?php
$num1 = 44;
$num2 = 4;
$result = $num1 & $num2;
print($result);
?>

This will print 4.


Flow Control
Programs must make decisions to be useful. Flow control refers to how a program
decides which action to take.
Functions are also a part of control flow and a key concept in programming.

If, Else and Else If

<?php
if ($a < $b)
print(“\$a is less than \$b”);
?>

?php
if ($a < $b)
print(“\$a is less than \$b”);
else
print(“\$a is not less than \$b”);
?>

<?php
if ($a < 50)
print(“\$a is less than 50”);
else if ($a > 50 and $a < 100)
print(“\$a is between 50-100”);
else
print(“\$a is greater than 100”);

?>

Switch

<?php
switch($a)
{
case “value1”:
<statements>;

case “value2”:
<statements>;
break;
..
..
..
default:
<statements for all other cases>
break;

?>
Looping with while, do-while, for, foreach

while
while (test expression)
{
<statements>;
}

Example:
while ($a < $b)
{
$a++;
}

do-while
do {
<statements>;
} while (test expression)

Example:
do
{
$a++;
} while ($a < $b)

for
for (expr1; expr2; expr3)
{
<statements>;
}

Example:
for ($i = 1; $i++; $i < 6)
{
print (“PHP is the best scripting language for the web”);
}

foreach
foreach (array as subexpression)
{
<statements>;
}

Example:
$four_wheeler=”Santro”;
$four_wheeler=”Indica”;
$four_wheeler=”Esteem”;
$four_wheeler=”Scode”;
foreach ($four_wheeler as $car)
{
print($car . “<br>””);
}
break and continue

The break keyword is used to exit a loop or to stop a Switch statement from falling
through. The break keyword breaks out of the loop within which it is included. If
there are 2 levels of Nesting and of the break is in the inner loop, the control breaks
the Inner loop and gets back to the outer loop.
Strings & Arrays
When working with Strings, you will want to do more operations than just echo them
out. Creating a string is quite easy – just assign a string to a variable. However,
more often, you will be obtaining strings from other sources like from a file or a
database.

String operators – concatenation and concatenation assignment.


Example :
a. Concatenation - $a . $b
b. Concatenation assignment - $a .= $b

Printing and echoing a string


Print “Value of string is $string”;
Echo “Value of string is $string”;

String Functions

Converting html characters in a string – use htmlspecialchars(). It converts


special HTML characters into HTML entities so they render as the literal characters
and not interpreted as regular HTML.
Htmlspecialchars(string str [, int quote_style])

Quote style can be ENT_COMPAT (only double quotes are converted), ENT_QUOTES
(both single and double quotes are converted) and ENT_NOQUOTES (neither type of
quotes is converted).

Lowercasing & Uppercasing – strtolower (string str) and strtoupper(string str)

Uppercasing First Letters– ucfirst(string str) and ucwords(string str)

Trimming & Chopping – ltrim(string str [, string charlist])


rtrim(string str [, string charlist])
trim(string str [, string charlist])
chop(string str [, string charlist])

ltrim removes all leading whitespace characters, rtrim removes all trailing whitespace
characters, trim removes both; chop is an alias to rtrim.
Characters that are considered as whitespace are as follows - \n, \r, \t, \0, \x)B and
space.
The trim family also supports an optional second argument which can take a charlist

For example - trim ($str, “\t\n”);


The above example removes tabs and newlines from $str.

Printf & sprintf


Printf(“Print only 2 decimals of %f as %.2f\n”,3.1432,3.1432);

Addslashes - addslashes($email)
This ensures that any single quote character in the email is escaped.
Length of a String – strlen(string str)

Substring

substr(string str, int start [, int length])


strstr(string haystack, string needle);
strchar(string haystack, string needle);
strrchar(string haystack, string needle);
strpos(string haystack, string needle [, int offset]);

Comparing Strings

(will return 0 if equal, +ve if str1 > str2 and –ve if str2 >str1)
Strcmp(string str1, string str2)
Strcasecmp(string str1, string str2)
You may limit the number of characters compared using strncmp or strncasecmp.

Regular Expressions

PHP allows manipulation of strings with Regular Expressions. Regular Expressions


(or Regex as they are called) are used to find patterns in text. They are a mini-
language of their own. Here, we will be dealing with the Perl compatible Regex.

Regular expressions are bracketed on either end by special delimited characters ,


usually /. There are 2 significant types of characters within Regex – regular
characters and metacharacters. For example, the regex /cat/ will match the string
cat. ON the other hand, the regex /[cat]/ uses the metacharacters [ and ]. And
this matches either c or a or t.

Metacharacter Description
\ Escape character
| Or functionality
() To group subexpressions (php|perl)class matches either
phpclass or perlclass
[] Match any one character inside the square brackets
{} Define a min, max number for matching z[{1,3} will
match z, zz, or zzz.
^ Match at start
$ Mach at end
* Match 0 or more of preceding character
? Match 0 or one of preceding character
+ Match 1 or one of preceding character
. Match any character

For matching case insensitive, use I after the pattern.


For example - /cat/i
Predefined characters and classes
\d Digit (same as [0-9])
\D Non didit (same as [^0-9])
\w Word character (same as [a-zA-Z0-9_])
\W Any nonword character
\s Whitespace character (same as [ \t\n\r\f])
\S Any non whitespace character

Matching a pattern
preg_match($pattern, $string)

Ex:
<?php
$string = “PHP is the best web scripting language”;
$pattern = /^PHP/;
if ($preg_match($pattern, $string))
print(“Found a match\n”);
?>

Replacing a matched pattern


preg_replace($pattern, $replacement, $string)

Splitting a String
$date = “04/08/06”;
$date_array = preg_split(“/[.\-\/]/”, $date);
(allowed delimiters are . or / or -)

Arrays

$numeric_index = array();
$numeric_index[0] = “John”;
$numeric_index[1] = “Jack”;
$numeric_index[2] = “Hard drive”;

Joining, Imploding & Exploding


User-defined Functions
Example of a user-defined PHP function:

<?php
function convert_temp($cent)
{
return ($cent * 1.8) + 32;
}
$cent = 24;
$fahr = convert_temp($cent);
print(‘The temperature in Fahrenheit is %.2’ . $fahr);
?>

Function Arguments – can include optional parameters as the last arguments in the
paranthetical list.
You may use func_get_args inside a function.

<?php
function addnums($num1, $num2)
{
if (func_num_args < 3)
return ($num1 + $num2);
else return “Error”;
}
$num1 = 4;
$num2 = 5;
$num3 = 3;
$sum = addnums($num1,$num2, $num3);
print(“The sum is “ . $sum);
?>
Classes & Objects
In pure OOP, everything is an object. The specifics of an object are defined with a
class. A class represents a practical guide to what fields and methods an object has.
Methods represent the kinds of messages an object understands.

In PHP, methods of an object are invoked with the -> operator.

$php_training = new training;


$php_training->chapter(‘oops’);

Basics

Every class definition begins with the keyword class, followed by a class name, which
can be any name that isn't a reserved word in PHP. Followed by a pair of curly
braces, which contains the definition of the classes members and methods. A
pseudo-variable, $this is available when a method is called from within an object
context. $this is a reference to the calling object (usually the object to which the
method belongs, but can be another object, if the method is called statically from the
context of a secondary object)

<?php
class A
{
function foo()
{
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")\n";
}
else {
echo "\$this is not defined.\n";
}
}
}

class B
{
function bar()
{
A::foo();
}
}

$a = new A();
$a->foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>

Output from the above example will be:


$this is defined (a)
$this is not defined.
$this is defined (b)
$this is not defined.

Constructors

A constructor is a function that is called when an object is instantiated. A


constructor will initialize an object.

PHP 5 allows developers to declare constructor methods for classes. Classes which
have a constructor method call this method on each newly-created object, so it is
suitable for any initialization that the object may need before it is used.
Note: Parent constructors are not called implicitly if the child class defines a
constructor. In order to run a parent constructor, a call to parent::__construct()
within the child constructor is required.
A Constructor of a class is simply a method with the exact same name as the
class. Here are 2 ways of declaring a constructor

<?php
class BaseClass {
function __construct() {
print "In BaseClass constructor\n";
}
}

class SubClass extends BaseClass {


function __construct() {
parent::__construct();
print "In SubClass constructor\n";
}
}

$obj = new BaseClass();


$obj = new SubClass();
?>
<?php
class orderClass {

}
?>

Destructor

void __destruct ( void )

PHP 5 introduces a destructor concept similar to that of other object-oriented


languages, such as C++. The destructor method will be called as soon as all
references to a particular object are removed or when the object is explicitly
destroyed.
<?php
class MyDestructableClass {
function __construct() {
print "In constructor\n";
$this->name = "MyDestructableClass";
}

function __destruct() {
print "Destroying " . $this->name . "\n";
}
}

$obj = new MyDestructableClass();


?>

Extends

A class can inherit methods and members of another class by using the extends
keyword in the declaration. It is not possible to extend multiple classes, a class can
only inherit one base class.

The inherited methods and members can be overridden, unless the parent class has
defined a method as final, by redeclaring them within the same name defined in the
parent class. It is possible to access the overridden method or members by
referencing them with parent::

<?php
class SimpleClass
{
// member declaration
public $var = 'a default value';
// method declaration
public function displayVar()
{
echo $this->var;
}
}

class ExtendClass extends SimpleClass


{
// Redefine the parent method
function displayVar()
{
echo "Extending class\n";
parent::displayVar();
}
}

$extended = new ExtendClass();


$extended->displayVar();
?>

The above example will output:


Extending Class
A default value
MySQL Database Interaction
Mysql is a popular and fast growing RDBMS. PHP provides specific APIs to connect
and interact with MySQL.

Connecting to Mysql
Mysql_connect(hostname, username, password)

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
?>

Selecting the database


mysql_select_db(<dbName>,<dbLink>) or die("Could not connect to database");

Closing the connection


mysql_close(<dblink>);

Running the query

$query = "select userid,password,type, user2contact,


user2employee from user
where userid = $username and
password = $userpwd";

$result = mysql_query($query);
$myrow = mysql_fetch_row($result);

Getting the number of rows returned

<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);

$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";

?>

Looping thru the results


while ($myrow = mysql_fetch_row($result))
{
print $myrow[0],$myrow[1];
}
Database creation

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}

$sql = 'CREATE DATABASE my_db';


if (mysql_query($sql, $link)) {
echo "Database my_db created successfully\n";
} else {
echo 'Error creating database: ' . mysql_error() . "\n";
}
?>
MySQL Persistent Connections
If, the connection overhead to a MySQL server is high, there is a possible advantage
to never throwing out old connections: allowing them to persist (hence,
“persistent”). There are definitely risks to this scheme; It is actually NOT
recommended.

mysql_pconnect — Open a persistent connection to a MySQL server

Establishes a persistent connection to a MySQL server.

mysql_pconnect() acts very much like mysql_connect() with two major


differences.

First, when connecting, the function would first try to find a (persistent) link that's
already open with the same host, username and password. If one is found, an
identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of
the script ends. Instead, the link will remain open for future use (mysql_close will
not close links established by mysql_pconnect()). This type of link is therefore
called 'persistent'.

Usage

The pconnect function is meant for enterprises with a high overhead on database
connections. Normally,each process holds its own database connection. However, if
there is a limit on the number of connections in a MySQL server, then you run into
problems with the normal mysql_connect.
That is where mysql_pconnect might be helpful. Even if there are more processes
running on the web server than the mysql server connection limit, these processes
can hold their connection and not error out.
In general, use mysql_connect for connecting to MySQL.

Persistent Connections with InnoDB table type


That MySQL supports 2 kinds of tables – ISAM and InnoDB. ISAM is the default.
ISAM tables do not support transaction oriented sql statements. InnoDB supports
transactions (start tran and end tran which are required for atomic operations). Do
not use transactions with mysql_pconnect.
MySQL Transactions
It is vitally important, at times, in which order queries run, and that all queries in a
group run, or none at all. A classic example would be an amount of money is taken
from one person's account, and put into another which would result in 2 transactions
being done and they should be done as an atomic operation. Transactions are
possible only with InnoDB tables. Make sure you use Type=InnoDB while creating
the tables.

For the above to occur, MySQL should be ACID compliant which it is.
ACID – Atomicity, Consistency, Isolation and Durable.
• Atomicity means several queries treated as one.
• Consistency means the integrity of the data should be maintained – that is, if
a document has a parent-child component, then both should be updated or
none at all.
• Isolation refers to the point that data being used for transaction one cannot
be used by another transaction until the first one is complete.
• Durability indicates that once a transaction is complete it is irreversible.

Transactions are wrapped in BEGIN and COMMIT statements. If the user wants to
avoid the commit due to an error, then ROLLBACK can be used.

Example of ROLLBACK:

mysql> BEGIN;
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO account values(500);


Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM account;


+---------+
|Amount |
+---------+
| 500 |
+---------+
1 row in set (0.02 sec)

mysql> ROLLBACK;
Query OK, 0 rows affected (0.01 sec)

mysql> SELECT * FROM account;


Empty set (0.00 sec)
Example of COMMIT

mysql> BEGIN;
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO account values(500);


Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM account;


+---------+
|Amount |
+---------+
| 500 |
+---------+
1 row in set (0.02 sec)

mysql> COMMIT;
Query OK, 0 rows affected (0.01 sec)

mysql> SELECT * FROM account;


+---------+
|Amount |
+---------+
| 500 |
+---------+
AJAX with PHP

AJAX = Asynchronous JavaScript And XML.

AJAX provides a new way creating better and more interactive web applications.
AJAX uses JavaScript to send and receive data between a web browser and a web
server. Please refer to figure above.

The AJAX technique makes web pages more responsive by exchanging data with the
web server behind the scenes, instead of reloading an entire web page each time a
user makes a change.

AJAX Uses XML And HTTP Requests

Web applications ususally submit input (using an HTML form) to a web server. After
the web server has processed the data, it will return a completely new web page to
the user.

Because the server returns a new web page each time the user submits input,
traditional web applications often refresh the screen and consequently run slowly.

With AJAX, web applications can send and retrieve data without reloading the whole
web page. This is done by sending HTTP requests to the server (behind the scenes),
and by modifying only parts of the web page using JavaScript when the server
returns data.

XML is commonly used as the format for receiving server data, although any format,
including plain text, can be used.

AJAX Example
The following example gives a better picture of AJAX in action. Enter the following
code into a .php file and the second piece of code into an html file. Open the html
file on your IIS or Apache server and check it out.
uc.php
<?php
if (isset($_GET['inputText']))
echo strtoupper($_GET['inputText']);
?>

uc.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax - PHP AJAX</title>
</head>
<body>
<script language="javascript" type="text/javascript">
// Get the HTTP Object
function getHTTPObject(){
if (window.ActiveXObject) return new
ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}
// Change the value of the outputText field
function setOutput(){
if(httpObject.readyState == 4){
document.getElementById('outputText').value = httpObject.responseText;
}
}
// Implement business logic
function doWork(){
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("GET", "upperCase.php?inputText="
+document.getElementById('inputText').value, true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput;
}
}
var httpObject = null;
</script>
<form name="testForm">
Input text: <input type="text" onkeyup="doWork();" name="inputText"
id="inputText" />
Output text: <input type="text" name="outputText" id="outputText" />
</form>
</body>
</html>
Explanation

a. What needs to be done


1. Listen on key-press event on the input field.
2. In case of key-press send a message to the PHP script
on the server.
3. Process the input with PHP and send back the result.
4. Capture the returning data and display it.

b. Ready State Values


0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete

c. Create a XMLHTTPrequest
To make a communication between the client and the server,
the client code needs to create a so called XMLHttpRequest
object. This object will be responsible for AJAX PHP
communication.

d. Catch the data and send the request


First of all we need to get a valid XMLHttpRequest object. If we have it then we can
send the value of the inputText field to the server script. We do this by composing an
URL with parameter, so in the PHP script we can use the $_GET super-global array to
catch the data. As next step we call the send() function of the XMLHttpRequest
object which will send our request to the server.

e. Catch the output


It's nice but how we can catch the response from the server?
To do this we need to use an other special property of the XMLHttpRequest object.
We can assign a function to this parameter and this function will be called if the state
of the object was changed.

You might also like