Monday, September 10, 2012

PHP MySQL Select

The SELECT statement is used to select data from a database.

Select Data From a Database Table

The SELECT statement is used to select data from a database.

Syntax

SELECT column_name(s)
FROM table_name
To learn more about SQL, please visit our SQL tutorial.
To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection.

Example

The following example selects all the data stored in the "Persons" table (The * character selects all the data in the table):
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM Persons");

while($row = mysql_fetch_array($result))
  {
  echo $row['FirstName'] . " " . $row['LastName'];
  echo "<br />";
  }

mysql_close($con);
?>
The example above stores the data returned by the mysql_query() function in the $result variable.
Next, we use the mysql_fetch_array() function to return the first row from the recordset as an array. Each call to mysql_fetch_array() returns the next row in the recordset. The while loop loops through all the records in the recordset. To print the value of each row, we use the PHP $row variable ($row['FirstName'] and $row['LastName']).
The output of the code above will be:
Peter Griffin
Glenn Quagmire


Display the Result in an HTML Table

The following example selects the same data as the example above, but will display the data in an HTML table:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM Persons");

echo "<table border='1'>
<
tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>
The output of the code above will be:
Firstname Lastname
Glenn Quagmire
Peter Griffin

PHP MySQL Insert

The INSERT INTO statement is used to insert new records in a table.

Insert Data Into a Database Table

The INSERT INTO statement is used to add new records to a database table.

Syntax

It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their values:
INSERT INTO table_name
VALUES (value1, value2, value3,...)
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

To learn more about SQL, please visit our SQL tutorial.To get PHP to execute the statements above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection.

Example

In the previous chapter we created a table named "Persons", with three columns; "Firstname", "Lastname" and "Age". We will use the same table in this example. The following example adds two new records to the "Persons" table:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin',35)");

mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire',33)");

mysql_close($con);
?>


Insert Data From a Form Into a Database

Now we will create an HTML form that can be used to add new records to the "Persons" table.
Here is the HTML form:
<html>
<body>

<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>

</body>
</html>
When a user clicks the submit button in the HTML form in the example above, the form data is sent to "insert.php".
The "insert.php" file connects to a database, and retrieves the values from the form with the PHP $_POST variables.
Then, the mysql_query() function executes the INSERT INTO statement, and a new record will be added to the "Persons" table.
Here is the "insert.php" page:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

mysql_close($con);
?>

How to Find and Replace Text in MySQL Database using SQL



How to Find and Replace Text in MySQL Database using SQL

MySQL database has a handy and simple string function REPLACE() that allows table data with the matching string (from_string) to be replaced by new string (to_string). This is useful if there is need to search and replace a text string which affects many records or rows, such as change of company name, postcode, URL or spelling mistake.

The syntax of REPLACE is REPLACE(text_string, from_string, to_string)
MySQL reference describes REPLACE as function that returns the string text_string with all occurrences of the string from_string replaced by the string to_string, where matching is case-sensitive when searching for from_string. text_string can be retrieved from the a field in the database table too. Most SQL command can be REPLACE() function, especially SELECT and UPDATE manipulation statement.

For example:
update TABLE_NAME set FIELD_NAME = replace(FIELD_NAME, ‘find this string’, ‘replace found string with this string’);
update client_table set company_name = replace(company_name, ‘Old Company’, ‘New Company’)
The above statement will replace all instances of ‘Old Company’ to ‘New Company’ in the field of company_name of client_table table.

Another example:
SELECT REPLACE(‘www.mysql.com’, ‘w’, ‘Ww’);
Above statement will return ‘WwWwWw.mysql.com’ as result.

Sunday, September 9, 2012

PHP Function array_flip()

Syntax

array array_flip ( array $input );

Definition and Usage

array_flip() returns an array in flip order, i.e. keys from input become values and values from input become keys.
If a value has several occurrences, the latest key will be used as its values, and all others will be lost.

Paramters

ParameterDescription
inputThe array to be fliped

Return Values

Returns FALSE if it fails otherwise fliped array.

Example

Try out following example:
<?php
$array = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);

print_r(array_flip($array));
?> 
This will produce following result:
Array ( [1] => a [2] => b [3] => c [4] => d [5] => e)

PHP Function array_filter()

Syntax

array array_filter ( array $input [, callback $callback] );

Definition and Usage

Iterates over each value in the input array passing them to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.

Paramters

ParameterDescription
inputThe array to iterate over
callbackThe callback function to use
If no callback is supplied, all entries of input equal to FALSE will be removed.

Return Values

Returns the filtered array.

Example

Try out following example:
<?php
function odd($var)
{
    return($var & 1);
}

function even($var)
{
    return(!($var & 1));
}

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);

echo "Odd :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));
?> 
This will produce following result:
Odd :
Array ( [a] => 1 [c] => 3 [e] => 5)
Even:
Array ( [0] => 6 [2] => 8 [4] => 10 [6] => 12)

PHP Function array_fill_keys()

Syntax

array array_fill_keys ( array $keys, mixed $value );

Definition and Usage

Fills an array with the value of the value parameter, using the values of the keys array as keys.

Paramters

ParameterDescription
keysArray of values that will be used as keys
valueEither an string or an array of values

Return Values

Returns the filled array

Example

Try out following example:
<?php
$keys = array('foo', 5, 10, 'bar');
$a = array_fill_keys($keys, 'banana');
print_r($a)
?> 
This will produce following result:
Array
(
    [foo] => banana
    [5] => banana
    [10] => banana
    [bar] => banana
)

PHP Function array_fill()

Syntax

array array_fill ( int $start_index, int $num, mixed $value );

Definition and Usage

Fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter.

Paramters

ParameterDescription
start_indexThe first index of the returned array
numNumber of elements to insert
valueValues to use filling

Return Values

Returns the filled array

Example

Try out following example:
<?php
$a = array_fill(5, 6, 'apple');
print_r($a)
?> 
This will produce following result:
Array
(
    [5]  => apple
    [6]  => apple
    [7]  => apple
    [8]  => apple
    [9]  => apple
    [10] => apple
)

Friday, September 7, 2012

PHP Function array_diff_ukey()

Syntax

array_diff_ukey ( $array1, $array2 [, $array3...,callback $key_compare_func] );

Definition and Usage

Compares the keys from array1 against the keys from array2 and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values.
Unlike array_diff_key() an user supplied callback function is used for the indices comparision, not internal function.

Paramters

ParameterDescription
array1Required. The first array is the array that the others will be compared with.
array2Required. An array to be compared with the first array
array3Optional. An array to be compared with the first array
key_compare_funcRequired. callback function to use. The callback function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Return Values

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Example

Try out following example:
<?php
function key_compare_func($v1,$v2) 
{
if ($v1===$v2)
 {
 return 0;
 }
if ($v1>v2)
 {
 return 1;
 }
else
 {
 return -1;
 }
}
$array1 = array(0=>"banana", 1=>"orange", 2=>"grapes");
$array2 = array(3=>"apple",1=>"apricot", 5=>"mango");
print_r(array_diff_ukey($array1,$array2,"key_compare_func"));
?> 
This will produce following result:
Array ( [0]=>banana [2]=>grapes )

PHP Function array_diff_uassoc()

Syntax

array_diff_uassoc ( $array1, $array2 [, $array3..., callback $key_compare_func] );

Definition and Usage

Compares array1 against array2 and returns the difference. Unlike array_diff() the array keys are used in the comparision.
Unlike array_diff_assoc() an user supplied callback function is used for the indices comparision, not internal function.

Paramters

ParameterDescription
array1Required. The array to compare from
array2Required. An array to be compared with the first array
array3Optional. An array to be compared with the first array
key_compare_funcRequired. callback function to use. The callback function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Return Values

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Example

Try out following example:
<?php
function key_compare_func($a, $b)
{
    if ($a === $b) {
        return 0;
    }
    return ($a > $b)? 1:-1;
}
$array1 = array("a" => "green", "b" => "brown", 
                                    "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_uassoc($array1, $array2, "key_compare_func");
print_r($result);

?> 
This will produce following result:
Array ( [b] => brown [c] => blue [0] => red )

PHP Function array_diff_key()

Syntax

array array_diff_key ( array $array1, array $array2 [, array $...] );

Definition and Usage

Compares array1 against array2 and returns the difference.

Paramters

ParameterDescription
array1Required. The first array is the array that the others will be compared with.
array2Required. An array to be compared with the first array
array3Optional. An array to be compared with the first array

Return Values

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Example

Try out following example:
<?php
$array1 = array('blue'  => 1, 'red'  => 2, 'purple' => 3);

$array2 = array('blue' => 4, 'yellow' => 5, 'cyan'  => 6);

var_dump(array_diff($input_array1, $input_array2));
?> 
This will produce following result:
array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(3)
}

PHP Function array_diff_assoc()

Syntax

array array_diff_assoc( array $array1, array $array2 [, array $array3...] );

Definition and Usage

Compares array1 against array2 and returns the difference. Unlike array_diff() the array keys are used in the comparision.

Paramters

ParameterDescription
array1Required. The array to compare from
array2Required. An array to be compared with the first array
array3Optional. An array to be compared with the first array

Return Values

Returns an array containing all the values from array1 that are not present in any of the other arrays with the same keys.

Example

Try out following example:
<?php
$input_array1 = array( a=>"orange", b=>"mango", c=>"banana");
$input_array2 = array( a=>"orange", b=>"apple", c=>"banana");
print_r(array_diff_assoc($input_array1, $input_array2));

$input_array1 = array( a=>"orange", b=>mango", c=>"banana");
$input_array2 = array( a=>"banana", b=>"apple", c=>"orange");
print_r(array_diff_assoc($input_array1, $input_array2));
?> 
This will produce following result:
Array ( [b] => mango )
Array ( [a] => orange [b] => mango [c] => banana )

PHP Function array_diff()

Syntax

array array_diff ( array $array1, array $array2 [, array $array3 ...] );

Definition and Usage

Compares array1 against array2 and returns the difference.

Paramters

ParameterDescription
array1Required. The first array is the array that the others will be compared with.
array2Required. An array to be compared with the first array
array3Optional. An array to be compared with the first array

Return Values

Returns an array containing the differennces.

Example

Try out following example:
<?php
$input_array1 = array("orange", "banana", "apple");
$input_array2 = array("orange", "mango", "apple");
print_r(array_diff($input_array1, $input_array2));
?> 
This will produce following result:
Array ( [1] => banana )

PHP Function array_count_values()

Syntax

array array_count_values ( array $input );

Definition and Usage

Returns an array using the values of the input array as keys and their frequency in input as values.

Paramters

ParameterDescription
inputThe array of values to count

Return Values

Returns an assosiative array of values from input as keys and their count as value.

Example

Try out following example:
<?php
$input_array = array("orange", "mango", "banan", "orange" );
print_r(array_count_values($input_array));
?> 
This will produce following result:
Array ( [orange] => 2 [mango] => 1 [banana => 1 )

PHP Function array_combine()

Syntax

array array_combine ( array $keys, array $values );

Definition and Usage

Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.

Paramters

ParameterDescription
keysArray of keys to be used
valuesArray of values to be used

Return Values

Returns the combined array, FALSE if the number of elements for each array isn't equal or if the arrays are empty.

Example

Try out following example:
<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?> 
This will produce following result:
Array([green] => avocado [red] => apple [yellow] => banana)

PHP Function array_chunk()

Syntax

array array_chunk ( array $input, int $size [, bool $preserve_keys] );

Definition and Usage

Chunks an array into size large chunks. The last chunk may contain less than size elements.

Paramters

ParameterDescription
inputThe array to work on
sizeThe size of each chunk
preserve_keysWhen set to TRUE keys will be preserved. Default is FALSE which will reindex the chunk numerically

Return Values

Returns a multidimensional numerically indexed array, starting with zero, with each dimension containing size elements.

Example

Try out following example:
<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?> 
This will produce following result:
Array (
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [2] => c
            [3] => d
        )

    [2] => Array
        (
            [4] => e
        )

)

PHP Function array_change_key_case()

Syntax

array array_change_key_case ( array $input [, int $case] )

Definition and Usage

Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.

Paramters

ParameterDescription
inputThe array to work on
caseEither CASE_UPPER or CASE_LOWER (default)

Return Values

Returns an array with its keys lower or uppercased, or false if input is not an array.

Example

Try out following example:
<?php
$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?> 
This will produce following result:
Array ( [FIRST] => 1 [SECOND] => 4 )

PHP Function array()

Syntax

array(key1 => value1, key2 => value2...)

Definition and Usage

Returns an array of the parameters. The parameters can be given an index with the => operator

Paramters

ParameterDescription
keyOptional. Specifies the key, of type numeric or string. If not set, an integer key is generated, starting at 0
valueRequired. Specifies the value

Return Values

Returns an array of the parameters.

Example

Try out following example
<?php
$a=array("a"=>"Dog", "b"=>"Cat", "c"=>"Horse");
print_r($a);
?> 
This will produce following result:
Array ( [a] => Dog [b] => Cat [c] => Horse )
The following example demonstrates how to create a two-dimensional array, how to specify keys for associative arrays, and how to skip-and-continue numeric indices in normal arrays.
<?php

$fruits = array (
    "fruits" => array("a"=>orange", "b"=>banana", "c"=>apple"),
    "numbers" => array(1, 2, 3, 4, 5, 6),
    "holes" => array("first", 5 => "second", "third")
);
?> 

PHP for PERL Developers

This chapter will list out major similarities and differences in between PHP and PERL. This will help PERL developers to understand PHP very quickly and avoid common mistakes.

Similarities:

  • Compiled scripting languages: Both Perl and PHP are scripting languages.This means that they are not used to produce native standalone executables in advance of execution.
  • Syntax: PHP's basic syntax is very close to Perl's, and both share a lot of syntactic features with C. Code is insensitive to whitespace, statements are terminated by semicolons, and curly braces organize multiple statements into a single block. Function calls start with the name of the function, followed by the actual arguments enclosed in parentheses and separated by commas.
  • Dollar-sign variables: All variables in PHP look like scalar variables in Perl: a name with a dollar sign ($) in front of it.
  • No declaration of variables: As in Perl, you don.t need to declare the type of a PHP variable before using it.
  • Loose typing of variables: As in Perl, variables in PHP have no intrinsic type other than the value they currently hold. You can store iether number or string in same type of variable.
  • Strings and variable interpolation: Both PHP and Perl do more interpretation of double-quoted strings ("string") than of singlequoted strings ('string').

Differences:

  • PHP is HTML-embedded: Although it is possible to use PHP for arbitrary tasks by running it from the command line, it is more typically connected to a Web server and used for producing Web pages. If you are used to writing CGI scripts in Perl, the main difference in PHP is that you no longer need to explicitly print large blocks of static HTML using print or heredoc statements and instead can simply write the HTML itself outside of the PHP code block.
  • No @ or % variables: PHP has one only kind of variable, which starts with a dollar sign ($). Any of the datatypes in the language can be stored in such variables, whether scalar or compound.
  • Arrays versus hashes: PHP has a single datatype called an array that plays the role of both hashes and arrays/lists in Perl.
  • Specifying arguments to functions: Function calls in PHP look pretty much like subroutine calls in Perl. Function definitions in PHP, on the other hand, typically require some kind of list of formal arguments as in C or Java which is not the csse in PERL.
  • Variable scoping in functions: In Perl, the default scope for variables is global. This means that top-level variables are visible inside subroutines. Often, this leads to promiscuous use of globals across functions. In PHP, the scope of variables within function definitions is local by default.
  • No module system as such: In PHP there is no real distinction between normal code files and code files used as imported libraries.
  • Break and continue rather than next and last: PHP is more like C langauge and uses break and continue instead of next and last statement.
  • No elsif: A minor spelling difference: Perl's elsif is PHP's elseif.
  • More kinds of comments: In addition to Perl-style (#) single-line comments, PHP offers C-style multiline comments (/* comment */ ) and Java-style single-line comments (// comment).
  • Regular expressions: PHP does not have a built-in syntax specific to regular expressions, but has most of the same functionality in its "Perl-compatible" regular expression functions.

PHP for C Developers

The simplest way to think of PHP is as interpreted C that you can embed in HTML documents. The language itself is a lot like C, except with untyped variables, a whole lot of Web-specific libraries built in, and everything hooked up directly to your favorite Web server.
The syntax of statements and function definitions should be familiar, except that variables are always preceded by $, and functions do not require separate prototypes.
Here we will put some similarities and diferences in PHP and C

Similarities:

  • Syntax: Broadly speaking, PHP syntax is the same as in C: Code is blank insensitive, statements are terminated with semicolons, function calls have the same structure (my_function(expression1, expression2)), and curly braces ({ and }) make statements into blocks. PHP supports C and C++-style comments (/* */ as well as //), and also Perl and shell-script style (#).
  • Operators: The assignment operators (=, +=, *=, and so on), the Boolean operators (&&, ||, !), the comparison operators (<,>, <=, >=, ==, !=), and the basic arithmetic operators (+, -, *, /, %) all behave in PHP as they do in C.
  • Control structures: The basic control structures (if, switch, while, for) behave as they do in C, including supporting break and continue. One notable difference is that switch in PHP can accept strings as case identifiers.
  • Function names: As you peruse the documentation, you.ll see many function names that seem identical to C functions.

Differences:

  • Dollar signs: All variables are denoted with a leading $. Variables do not need to be declared in advance of assignment, and they have no intrinsic type.
  • Types: PHP has only two numerical types: integer (corresponding to a long in C) and double (corresponding to a double in C). Strings are of arbitrary length. There is no separate character type.
  • Type conversion: Types are not checked at compile time, and type errors do not typically occur at runtime either. Instead, variables and values are automatically converted across types as needed.
  • Arrays: Arrays have a syntax superficially similar to C's array syntax, but they are implemented completely differently. They are actually associative arrays or hashes, and the index can be either a number or a string. They do not need to be declared or allocated in advance.
  • No structure type: There is no struct in PHP, partly because the array and object types together make it unnecessary. The elements of a PHP array need not be of a consistent type.
  • No pointers: There are no pointers available in PHP, although the typeless variables play a similar role. PHP does support variable references. You can also emulate function pointers to some extent, in that function names can be stored in variables and called by using the variable rather than a literal name.
  • No prototypes: Functions do not need to be declared before their implementation is defined, as long as the function definition can be found somewhere in the current code file or included files.
  • Memory management: The PHP engine is effectively a garbage-collected environment (reference-counted), and in small scripts there is no need to do any deallocation. You should freely allocate new structures - such as new strings and object instances. IN PHP5, it is possible to define destructors for objects, but there is no free or delete. Destructors are called when the last reference to an object goes away, before the memory is reclaimed.
  • Compilation and linking: There is no separate compilation step for PHP scripts.
  • Permissiveness: As a general matter, PHP is more forgiving than C (especially in its type system) and so will let you get away with new kinds of mistakes. Unexpected results are more common than errors.

Object Oriented Programming in PHP

We can imagine our universe made of different objects like sun, earth, moon etc. Similarly we can imagine our car made of different objects like wheel, steering, gear etc. Same way there is object oriented programming concepts which assume everything as an object and implement a software using different objects.

Object Oriented Concepts:

Before we go in detail, lets define important terms related to Object Oriented Programming.
  • Class: This is a programmer-defined datatype, which includes local functions as well as local data. You can think of a class as a template for making many instances of the same kind (or class) of object.
  • Object: An individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it. Objects are also known as instance.
  • Member Variable: These are the variables defined inside a class. This data will be invisible to the outside of the class and can be accessed via member functions. These variables are called attribute of the object once an object is created.
  • Member function: These are the function defined inside a class and are used to access object data.
  • Inheritance: When a class is defined by inheriting existing function of a parent class then it is called inheritance. Here child class will inherit all or few member functions and variables of a parent class.
  • Parent class: A class that is inherited from by another class. This is also called a base class or super class.
  • Child Class: A class that inherits from another class. This is also called a subclass or derived class.
  • Polymorphism: This is an object oriented concept where same function can be used for different purposes. For example function name will remain same but it make take different number of arguments and can do different task.
  • Overloading: a type of polymorphism in which some or all of operators have different implementations depending on the types of their arguments. Similarly functions can also be overloaded with different implementation.
  • Data Abstraction: Any representation of data in which the implementation details are hidden (abstracted).
  • Encapsulation: refers to a concept where we encapsulate all the data and member functions together to form an object.
  • Constructor: refers to a special type of function which will be called automatically whenever there is an object formation from a class.
  • Destructors: refers to a special type of function which will be called automatically whenever an object is deleted or goes out of scope.

Defining PHP Classes:

The general form for defining a new class in PHP is as follows:
<?php
class phpClass{
   var $var1;
   var $var2 = "constant string";
   function myfunc ($arg1, $arg2) {
      [..]
   }
   [..]
}
?>
Here is the description of each line:
  • The special form class, followed by the name of the class that you want to define.
  • A set of braces enclosing any number of variable declarations and function definitions.
  • Variable declarations start with the special form var, which is followed by a conventional $ variable name; they may also have an initial assignment to a constant value.
  • Function definitions look much like standalone PHP functions but are local to the class and will be used to set and access object data.

Example:

Here is an example which defines a class of Books type:
<?php
class  Books{
    /* Member variables */
    var $price;
    var $title;
    /* Member functions */
    function setPrice($par){
       $this->$price = $var;
    }
    function getPrice(){
       echo $this->$price ."<br/>";
    }
    function setTitle($par){
       $this->$title = $par;
    }
    function getTitle(){
       echo $this->$title ." <br/>";
    }
}
?>
The variable $this is a special variable and it refers to the same object ie. itself.

Creating Objects in PHP

Once you defined your class, then you can create as many objects as you like of that class type. Following is an example of how to create object using new operator.
   $physics = new Books;
   $maths = new Books;
   $chemistry = new Books;
Here we have created three objects and these objects are independent of each other and they will have their existance separately. Next we will see how to access member function and process member variables.

Calling Member Functions

After creating your objects, you will be able to call member functions related to that object. One member function will be able to process member variable of related object only.
Following example shows how to set title and prices for the three books by calling member functions.
   $physics->setTitle( "Physics for High School" );
   $chemistry->setTitle( "Advanced Chemistry" );
   $maths->setTitle( "Algebra" );

   $physics->setPrice( 10 );
   $chemistry->setPrice( 15 );
   $maths->setPrice( 7 );
Now you call another member functions to get the values set by in above example:
   $physics->getTitle();
   $chemistry->getTitle();
   $maths->getTitle();
   $physics->getPrice();
   $chemistry->getPrice();
   $maths->getPrice();
This will produce follwoing result:
  Physics for High School
  Advanced Chemistry
  Algebra
  10
  15
  7

Constructor Functions:

Constructor Functions are special type of functions which are called automatically whenever an object is created. So we take full advantage of this behaviour, by initializing many things through constructor functions.
PHP provides a special function called __construct() to define a constructor. You can pass as many as arguments you like into the constructor function.
Following example will create one constructor for Books class and it will initialize price and title for the book at the time of object creation.
function __construct( $par1, $par2 ){
   $price = $par1;
   $title = $par2;
}
Now we don't need to call set function separately to set price and title. We can initialize these two member variables at the time of object creation only. Check following example below:
   $physics = new Books( "Physics for High School", 10 );
   $maths = new Books ( "Advanced Chemistry", 15 );
   $chemistry = new Books ("Algebra", 7 );

   /* Get those set values */
   $physics->getTitle();
   $chemistry->getTitle();
   $maths->getTitle();

   $physics->getPrice();
   $chemistry->getPrice();
   $maths->getPrice();
This will produce following result:
  Physics for High School
  Advanced Chemistry
  Algebra
  10
  15
  7

Destructor:

Like a constructor function you can define a destructor function using function __destruct(). You can release all the resourceses with-in a destructor.

Inheritance:

PHP class definitions can optionally inherit from a parent class definition by using the extends clause. The syntax is as follows:
  class Child extends Parent {
     <definition body>
  }
The effect of inheritance is that the child class (or subclass or derived class) has the following characteristics:
  • Automatically has all the member variable declarations of the parent class.
  • Automatically has all the same member functions as the parent, which (by default) will work the same way as those functions do in the parent.
Following example inherit Books class and adds more functionality based on the requirement.
class Novel extends Books{
   var publisher;
   function setPublisher($par){
     $this->$publisher = $par;
   }
   function getPublisher(){
     echo $this->$publisher. "<br />";
   }
}
Now apart from inherited functions, class Novel keeps two additional member functions.

Function Overriding:

Function definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class.
In the follwoing example getPrice and getTitle functions are overriden to retrun some values.
    function getPrice(){
       echo $this->$price . "<br/>";
       return $this->$price;
    }
    function getTitle(){
       echo $this->$title . "<br/>";
       return $title;
    }

Public Members:

Unless you specify otherwise, properties and methods of a class are public. That is to say, they may be accessed in three possible situations:
  • From outside the class in which it is declared
  • From within the class in which it is declared
  • From within another class that implements the class in which it is declared
Till now we have seen all members as public members. If you wish to limit the accessibility of the members of a class then you define class members as private or protected.

Private members:

By designating a member private, you limit its accessibility to the class in which it is declared. The private member cannot be referred to from classes that inherit the class in which it is declared and cannot be accessed from outside the class.
A class member can be made private by using private keyword infront of the member.
class MyClass {
   private $car = "skoda";
   $driver = "SRK";

   function __construct($par) {
      // Statements here run every time
      // an instance of the class
      // is created.
   }
   function myPublicFunction() {
      return("I'm visible!");
   }
   private function myPrivateFunction() {
      return("I'm  not visible outside!");
   }
}
When MyClass class is inherited by another class using extends, myPublicFunction() will be visible, as will $driver. The extending class will not have any awareness of or access to myPrivateFunction and $car, because they are declared private.

Protected members:

A protected property or method is accessible in the class in which it is declared, as well as in classes that extend that class. Protected members are not available outside of those two kinds of classes. A class member can be made protected by using protected keyword infront of the member.
Here is different version of MyClass:
class MyClass {
   protected $car = "skoda";
   $driver = "SRK";

   function __construct($par) {
      // Statements here run every time
      // an instance of the class
      // is created.
   }
   function myPublicFunction() {
      return("I'm visible!");
   }
   protected function myPrivateFunction() {
      return("I'm  visible in child class!");
   }
}

Interfaces:

Interfaces are defined to provide a common function names to the implementors. Different implementors can implement those interfaces according to theri requirements. You can say, interfaces are skeltons which are implemented by developers.
As of PHP5, it is possible to define an interface, like this:
interface Mail {
   public function sendMail();
}
Then, if another class implemented that interface, like this:
class Report implements Mail {
   // sendMail() Definition goes here
}

Constants:

A constant is somewhat like a variable, in that it holds a value, but is really more like a function because a constant is immutable. Once you declare a constant, it does not change.
Declaring one constant is easy, as is done in this version of MyClass:
class MyClass {
   const requiredMargin = 1.7;
   function __construct($incomingValue) {
      // Statements here run every time
      // an instance of the class
      // is created.
   }
}
In this class, requiredMargin is a constant. It is declared with the keyword const, and under no circumstances can it be changed to anything other than 1.7. Note that the constant's name does not have a leading $, as variable names do.

Abstract Classes:

An abstract class is one that cannot be instantiated, only inherited. You declare an abstract class with the keyword abstract, like this:
When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same visibillity.
abstract class MyAbstractClass {
   abstract function myAbstractFunction() {
   }
}
Note that function definitions inside an abstract class must also be preceded by the keyword abstract. It is not legal to have abstract function definitions inside a non-abstract class.

Static Keyword:

Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can).
Try out following example:
<?php
class Foo
{
    public static $my_static = 'foo';

    public function staticValue() {
        return self::$my_static;
    }
}
print Foo::$my_static . "\n";
$foo = new Foo();
print $foo->staticValue() . "\n";

Final Keyword:

PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
Following example results in Fatal error: Cannot override final method BaseClass::moreTesting()
<?php
class BaseClass {
   public function test() {
       echo "BaseClass::test() called<br>";
   }
  
   final public function moreTesting() {
       echo "BaseClass::moreTesting() called<br>";
   }
}

class ChildClass extends BaseClass {
   public function moreTesting() {
       echo "ChildClass::moreTesting() called<br>";
   }
}
?>

Calling parent constructors:

Instead of writing an entirely new constructor for the subclass, let's write it by calling the parent's constructor explicitly and then doing whatever is necessary in addition for instantiation of the subclass. Here's a simple example:
class Name
{
   var $_firstName;
   var $_lastName;
   function Name($first_name, $last_name)
   {
     $this->_firstName = $first_name;
     $this->_lastName = $last_name;
   }
   function toString() {
     return($this->_lastName .", " .$this->_firstName);
   }
}
class NameSub1 extends Name
{
   var $_middleInitial;
   function NameSub1($first_name, $middle_initial, $last_name) {
       Name::Name($first_name, $last_name);
       $this->_middleInitial = $middle_initial;
   }
   function toString() {
       return(Name::toString() . " " . $this->_middleInitial);
   }
}
In this example, we have a parent class (Name), which has a two-argument constructor, and a subclass (NameSub1), which has a three-argument constructor. The constructor of NameSub1 functions by calling its parent constructor explicitly using the :: syntax (passing two of its arguments along) and then setting an additional field. Similarly, NameSub1 defines its nonconstructor toString() function in terms of the parent function that it overrides.
NOTE: A constructor can be defined with the same name as the name of a class. It is defined in above example.

PHP and XML

XML is a markup language that looks a lot like HTML. An XML document is plain text and contains tags delimited by < and >.There are two big differences between XML and HTML:
  • XML doesn't define a specific set of tags you must use.
  • XML is extremely picky about document structure.
XML gives you a lot more freedom than HTML. HTML has a certain set of tags: the <a></a> tags surround a link, the <p> startsa paragraph and so on. An XML document, however, can use any tags you want. Put <rating></rating> tags around a movie rating, >height></height> tags around someone's height. Thus XML gives you option to device your own tags.
XML is very strict when it comes to document structure. HTML lets you play fast and loose with some opening and closing tags. BUt this is not the case with XML.

HTML list that's not valid XML:

<ul>
<li>Braised Sea Cucumber
<li>Baked Giblets with Salt
<li>Abalone with Marrow and Duck Feet
</ul>
This is not a valid XML document because there are no closing </li> tags to match up with the three opening <li> tags. Every opened tag in an XML document must be closed.

HTML list that is valid XML:

<ul>
<li>Braised Sea Cucumber</li>
<li>Baked Giblets with Salt</li>
<li>Abalone with Marrow and Duck Feet</li>
</ul>

Parsing an XML Document:

PHP 5's new SimpleXML module makes parsing an XML document, well, simple. It turns an XML document into an object that provides structured access to the XML.
To create a SimpleXML object from an XML document stored in a string, pass the string to simplexml_load_string( ). It returns a SimpleXML object.

Example:

Try out following example:
<?php

$channel =<<<_XML_
<channel>
<title>What's For Dinner<title>
<link>http://menu.example.com/<link>
<description>Choose what to eat tonight.</description>
</channel>
_XML_;

$xml = simplexml_load_string($channel);
print "The $xml->title channel is available at $xml->link. ";
print "The description is \"$xml->description\"";
?>
It will produce following result:
The What's For Dinner channel is available at http://menu.example.com/. The description is "Choose what to eat tonight."

Generating an XML Document:

SimpleXML is good for parsing existing XML documents, but you can't use it to create a new one from scratch.
The easiest way to generate an XML document is to build a PHP array whose structure mirrors that of the XML document and then to iterate through the array, printing each element with appropriate formatting.

Example:

Try out following example:
<?php

$channel = array('title' => "What's For Dinner",
                 'link' => 'http://menu.example.com/',
                 'description' => 'Choose what to eat tonight.');
print "<channel>\n";
foreach ($channel as $element => $content) {
   print " <$element>";
   print htmlentities($content);
   print "</$element>\n";
}
print "</channel>";
?>
It will produce following result:
<channel>
<title>What's For Dinner</title>
<link>http://menu.example.com/</link>
<description>Choose what to eat tonight.</description>
</channel></html>

PHP and AJAX

What is AJAX ?

  • AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS and Java Script.
  • Conventional web application trasmit information to and from the sever using synchronous requests. This means you fill out a form, hit submit, and get directed to a new page with new information from the server.
  • With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the results and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server.

PHP and AJAX Example:

To clearly illustrate how easy it is to access information from a database using Ajax and PHP, we are going to build MySQL queries on the fly and display the results on "ajax.html". But before we proceed, lets do ground work. Create a table using the following command.
NOTE: We are asuing you have sufficient privilege to perform following MySQL operations
CREATE TABLE `ajax_example` (
  `name` varchar(50) NOT NULL,
  `age` int(11) NOT NULL,
  `sex` varchar(1) NOT NULL,
  `wpm` int(11) NOT NULL,
  PRIMARY KEY  (`name`)
) 
Now dump the following data into this table using the foloowing SQL statements
INSERT INTO `ajax_example` VALUES ('Jerry', 120, 'm', 20);
INSERT INTO `ajax_example` VALUES ('Regis', 75, 'm', 44);
INSERT INTO `ajax_example` VALUES ('Frank', 45, 'm', 87);
INSERT INTO `ajax_example` VALUES ('Jill', 22, 'f', 72);
INSERT INTO `ajax_example` VALUES ('Tracy', 27, 'f', 0);
INSERT INTO `ajax_example` VALUES ('Julie', 35, 'f', 90);

Client Side HTML file

Now lets have our client side HTML file which is ajax.html and it will have following code
<html>
<body>
<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
 var ajaxRequest;  // The variable that makes Ajax possible!
 
 try{
   // Opera 8.0+, Firefox, Safari
   ajaxRequest = new XMLHttpRequest();
 }catch (e){
   // Internet Explorer Browsers
   try{
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
   }catch (e) {
      try{
         ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }catch (e){
         // Something went wrong
         alert("Your browser broke!");
         return false;
      }
   }
 }
 // Create a function that will receive data 
 // sent from the server and will update
 // div section in the same page.
 ajaxRequest.onreadystatechange = function(){
   if(ajaxRequest.readyState == 4){
      var ajaxDisplay = document.getElementById('ajaxDiv');
      ajaxDisplay.value = ajaxRequest.responseText;
   }
 }
 // Now get the value from user and pass it to
 // server script.
 var age = document.getElementById('age').value;
 var wpm = document.getElementById('wpm').value;
 var sex = document.getElementById('sex').value;
 var queryString = "?age=" + age ;
 queryString +=  "&wpm=" + wpm + "&sex=" + sex;
 ajaxRequest.open("GET", "ajax-example.php" + 
                              queryString, true);
 ajaxRequest.send(null); 
}
//-->
</script>
<form name='myForm'>
Max Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' />
<br />
Sex: <select id='sex'>
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onclick='ajaxFunction()' 
                              value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>
NOTE: The way of passing variables in the Query is according to HTTP standard and the have formA
URL?variable1=value1;&variable2=value2;
Now the above code will give you a screen as given below

NOTE: This is dummy screen and would not work
Max Age: 

Max WPM:

Sex:
Your result will display here

Server Side PHP file

So now your client side script is ready. Now we have to write our server side script which will fetch age, wpm and sex from the database and will send it back to the client. Put the following code into "ajax-example.php" file
<?php
$dbhost = "localhost";
$dbuser = "dbusername";
$dbpass = "dbpassword";
$dbname = "dbname";
 //Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
 //Select Database
mysql_select_db($dbname) or die(mysql_error());
 // Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
 // Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
 //build query
$query = "SELECT * FROM ajax_example WHERE sex = '$sex'";
if(is_numeric($age))
 $query .= " AND age <= $age";
if(is_numeric($wpm))
 $query .= " AND wpm <= $wpm";
 //Execute query
$qry_result = mysql_query($query) or die(mysql_error());

 //Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";

// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
 $display_string .= "<tr>";
 $display_string .= "<td>$row[name]</td>";
 $display_string .= "<td>$row[age]</td>";
 $display_string .= "<td>$row[sex]</td>";
 $display_string .= "<td>$row[wpm]</td>";
 $display_string .= "</tr>";
 
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>

Now try by entering a valid value in "Max Age" or any other box and then click Query MySQL button.
Max Age: 

Max WPM:

Sex:
Your result will display here

If you have successfully completed this lesson then you know how to use MySQL, PHP, HTML, and Javascript in tandem to write Ajax applications.

PHP Date and Time

Dates are so much part of everyday life that it becomes easy to work with them without thinking. PHP also provides powerful tools for date arithmetic that make manipulating dates easy.

Getting the Time Stamp with time():

PHP's time() function gives you all the information that you need about the current date and time. It requires no arguments but returns an integer.
The integer returned by time() represents the number of seconds elapsed since midnight GMT on January 1, 1970. This moment is known as the UNIX epoch, and the number of seconds that have elapsed since then is referred to as a time stamp.
<?php
print time();
?>
It will produce following result:
948316201
This is something difficult to understand. But PHP offers excellent tools to convert a time stamp into a form that humans are comfortable with.

Converting a Time Stamp with getdate():

The function getdate() optionally accepts a time stamp and returns an associative array containing information about the date. If you omit the time stamp, it works with the current time stamp as returned by time().
Following table lists the elements contained in the array returned by getdate().
KeyDescriptionExample
secondsSeconds past the minutes (0-59)20
minutesMinutes past the hour (0 - 59)29
hoursHours of the day (0 - 23)22
mdayDay of the month (1 - 31)11
wdayDay of the week (0 - 6)4
monMonth of the year (1 - 12)7
yearYear (4 digits)1997
ydayDay of year ( 0 - 365 )19
weekdayDay of the weekThursday
monthMonth of the yearJanuary
0Timestamp948370048
Now you have complete control over date and time. You can format this date and time in whatever format you wan.

Example:

Try out following example
<?php
$date_array = getdate();
foreach ( $date_array as $key => $val )
{
   print "$key = $val<br />";
}
$formated_date  = "Today's date: ";
$formated_date .= $date_array[mday] . "/";
$formated_date .= $date_array[mon] . "/";
$formated_date .= $date_array[year];

print $formated_date;
?>
It will produce following result:
seconds = 27
minutes = 25
hours = 11
mday = 12
wday = 6
mon = 5
year = 2007
yday = 131
weekday = Saturday
month = May
0 = 1178994327
Today's date: 12/5/2007

Converting a Time Stamp with date():

The date() function returns a formatted string representing a date. You can exercise an enormous amount of control over the format that date() returns with a string argument that you must pass to it.
date(format,timestamp)
The date() optionally accepts a time stamp if ommited then current date and time will be used. Any other data you include in the format string passed to date() will be included in the return value.
Following table lists the codes that a format string can contain:
FormatDescriptionExample
a'am' or 'pm' lowercasepm
A'AM' or 'PM' uppercasePM
dDay of month, a number with leading zeroes20
DDay of week (three letters)Thu
FMonth nameJanuary
hHour (12-hour format - leading zeroes)12
HHour (24-hour format - leading zeroes)22
gHour (12-hour format - no leading zeroes)12
GHour (24-hour format - no leading zeroes)22
iMinutes ( 0 - 59 )23
jDay of the month (no leading zeroes20
l (Lower 'L')Day of the weekThursday
LLeap year ('1' for yes, '0' for no)1
mMonth of year (number - leading zeroes)1
MMonth of year (three letters)Jan
rThe RFC 2822 formatted dateThu, 21 Dec 2000 16:01:07 +0200
nMonth of year (number - no leading zeroes)2
sSeconds of hour20
UTime stamp948372444
yYear (two digits)06
YYear (four digits)2006
zDay of year (0 - 365)206
ZOffset in seconds from GMT+5

Example:

Try out following example
<?php
print date("m/d/y G.i:s<br>", time());
print "Today is ";
print date("j of F Y, \a\\t g.i a", time());
?>
It will produce following result:
01/20/00 13.27:55
Today is 20 of January 2000, at 1.27 pm
Hope you have good understanding on how to format date and time according to your requirement.

Tuesday, August 28, 2012

Display current date in php


echo date('d-m-Y');

Split a data by comma

$Add_array = split("[,]",$Address);
   for ($i =0; $i < count($Add_array); $i++){  
   echo($Add_array[$i]);
     }

Find an element in array - php code

<?php
$os 
= array("Mac""NT""Irix""Linux");
if (
in_array("Irix"$os)) {
    echo 
"Got Irix";
}
if (
in_array("mac"$os)) {
    echo 
"Got mac";
}
?>
The second condition fails because in_array() is case-sensitive, so the program above will display:
Got Irix
 

Numbers and strings

Numbers and strings

Operators

We have already seen how to use functions, such as sqrt, to manipulate values in PHP. For the most common operations, though, PHP provides symbolic shortcuts for the operations, such as + for adding two values together, or * for multiplying two values. Such symbols are called operators.
PHP includes about 30 operators, though we'll only cover the 10 or so that appear frequently in programs. The most recognizable would be + for addition, - for subtraction or negation, * for multiplication, and / for division. We can use these to enhance our range selection page so that it displays the midpoint in the range:
<p>From the range <?php echo $form_begin; ?>
to <?php echo $form_end; ?> I have selected the random number
<?php echo rand($form_begin, $form_end); ?>.  The midpoint is <?php
    $average = ($form_begin + $form_end) / 2;
    echo $average;
?>.</p>
PHP observes the traditional order of operations: Negation comes first, followed by division and multiplication in left-to-right order, followed by addition and subtraction in left-to-right order. You can use parentheses when you want to indicate a different order of operations; in the above example, we had to use the parentheses; otherwise, PHP would add form_begin to half of $form_end, which wouldn't be the average of the two values.
There is another operator worth mentioning: The remainder operator, represented by the percent sign. When placed between two numbers, the resulting value is whatever remainder results when the first number is divided by the second number; for example, 28 % 9 would yield 1, since 9 goes into 28 three times with a remainder of 1. The remainder operator lies at the same precedence level as multiplication and division in PHP.
Note that one operator that is not on the list: There is no operator for exponentiation. People often expect the caret ('^') to do this; PHP allows you to use a caret to operator on two numbers, but what it does is fairly obscure and rarely very useful. (You don't need to worry about it, but what it does is a bitwise exclusive or, where it computes the number whose binary representation is 1 in each place where the two numbers' binary representations are different.) When you want to raise one number to another power, you can instead use PHP's pow function: The tenth power of 1.5, for example, can be found with pow(1.5, 10).

5.2. Types

As PHP processes a program, it works with a variety of categories of information, each called a type. Thus far, we have glossed over the distinction, but it is an important one.
In fact, PHP works with two different types of numbers: integers and floating-point numbers. Integers are numbers represented in a format that allow no fractional parts (and allow numbers such as 0 or 2 or −158), whereas floating-point numbers are represented in a format that allows fraction parts (such as 3.14159 and 1.5). Whenever a number is written with a decimal point, it is a floating-point number; thus, if you write 1.0, you're talking about the floating-point value 1, which doesn't behave exactly the same as the integer value 1.
For those who have programmed in other languages based on C: PHP's division operator always produces a floating-point result. (Most other C-derived languages ape C's rules for dividing two integers, where the remainder is ignored so the result is still an integer. In PHP, an expression such as 1 / 2 actually yields 0.5 as a beginner would expect.)
Most of the time you don't need to worry about the distinction between floating-point numbers and integers; PHP freely converts integers to floating-point numbers when necessary. One situation where it can appear is with rounding problems, such as with the following statement.
echo 10000000000000000 - 9999999999999999;
This statement outputs 0 on some computers, because those computers can't store integers so big, and so PHP uses floats instead... and it happens that they are both approximated with the same float.
If there's some reason you want to convert between the two, you can use PHP's intval and floatval functions.

5.3. Strings

PHP includes many other types for values that aren't numbers. One of the most important such is the string, which is a value representing a sequence of several characters, such as a word, a sentence, or a nonsensical stream of punctuation.
To refer to a particular string value, you can use a set of quotation marks enclosing the characters you want to include in the string. The following statement makes the variable $sentence refer to a famed novel's opening sentence.
$name = "It was the best of times; it was the worst of times.";
When you enclose a string in quotation marks, the contents of the quotation marks are not interpreted by PHP: It simply places the raw characters into the string. Suppose I type:
$expr = "rand(1, 100)";
PHP does not use the rand function here: It simply creates a string consisting of 12 characters, starting with the letter r and ending with the close-parenthesis character. If we omitted the quotation marks, of course PHP would call the rand function to retrieve a random number between 1 and 100.
One exception (and the only exception) to this rule is variable names: When you include a variable name in a string, PHP will substitute the variable's value in place of the name. Suppose I write this:
echo "The range is $form_begin to $form_end. ";
echo "The midpoint is ($form_begin + $form_end) / 2. ";
echo "The chosen number is rand($form_begin, $form_end). ";
The PHP interpreter would substitute the values of the variables whenever they occur; but it would not attempt to apply the operators or call the functions. What we would see on the Web browser, then, is the following.
The range is 10 to 20. The midpoint is (10 + 20) / 2. The chosen number is rand(10, 20).
Of course, that's probably not what we want. There are several ways of getting around this. One is to first assign a variable to refer to the desired value, and then to use that variable inside the string. But another approach worth knowing about is the catenation operator '.', which you can use to join two values into a string. The following is how we could modify our example.
echo "The range is $form_begin to $form_end. ";
echo "The midpoint is " . (($form_begin + $form_end) / 2) . ". ";
echo "The chosen number is " . rand($form_begin, $form_end) . ". ";
As an example, the final line says to catenate the string The chosen number is with the value generated by rand, which itself should be catenated with the string .. Note the space that has carefully been added inside the first string after is: Without this, the output would omit the space, as in The chosen number is17..
The catenation operator has the same priority level as addition and subtraction. As a result, the following would be incorrect.
echo "The sum is " . $form_begin + $form_end;   // WRONG!
PHP would first catenate The sum is with $form_begin, resulting in a string such as The sum is 20. Then it would attempt to interpret this as a number so that it could add $form_end to it. It would not work as we would expect. For this reason, I recommend developing the habit of using parentheses whenever you try to combine other operators with catenation, even when it is not necessary. The above midpoint example illustrates this: Even though there the parentheses were unnecessary since division occurs at a higher level than catenation, I went ahead and used parentheses anyway.
We've seen that variable names in double quotation marks will be replaced with the variable values. But that brings up a question: What if you don't want this substitution to occur? There are two answers that PHP provides. First, you can prefix the relevant dollar sign with a backslash, as in "\$choice is $choice"; in this example, the first dollar sign won't be treated as part of a variable name, but the second will, so the string will translate to something like $choice is 17. You can do the same backslash trick when you want to a quotation mark to appear inside the string, or when you want a backslash as part of the string.
Backslashes can also be used to insert other characters. Most significantly, '\n' inserts a newline character into a string. Since line breaks aren't automatically inserted between echo statement, a PHP script that echoes a large amount of information would normally create one large line, which can be quite difficult to read for somebody who tries to read the generated HTML source. (Of course, the browser ignores line breaks anyway.) For this reason, I'd be inclined to instead write our earlier example with three echo statements as the following instead.
echo "The range is $form_begin to $form_end.\n";
echo "The midpoint is " . (($form_begin + $form_end) / 2) . ".\n";
echo "The chosen number is " . rand($form_begin, $form_end) . ".\n";
Note the '\n' that follows each period. This leads the generated HTML to include three separate lines rather than one long line. Again, the browser will display the HTML the same when we have spaces instead of newlines, but a user who chooses to read the HTML source will have an easier time with the newlines inserted. (You can also use '\t' to specify a tab character, but this is not as useful.)
Sometimes the number of backslashes can get a bit cumbersome, so PHP provides another way, too: You can enclose the string in single quotation marks. Variable substitution never occurs for a string enclosed in single quotation marks. (I won't use this single-quotation technique, but many PHP programmers use single quotes as a matter of habit.)

Conditional execution

if statements

Suppose we wanted our random number generation program to work even when the user enters the two ends of the range in the opposite order. What we would want is a way to test whether they are inverted, and then to silently swap them back into the proper order before proceeding. We can do this using what is called an if statement. The following solution illustrates how it would work.
<?php import_request_variables("pg""form_"); ?>
<html>
<head>
<title>Generate Random Number</title>
</head>

<body>
<p>From the range <?php
    if($form_begin > $form_end) {
        $old_begin = $form_begin;
        $form_begin = $form_end;
        $form_end = $old_begin;
    }
    echo $form_begin;
?> to <?php
    echo $form_end;
?> I have selected the random number <?php
    echo rand($form_begin, $form_end);
?>.</p>
</body>
</html>
An if statement is always followed by a set of parentheses enclosing some yes/no expression. Following that is a set of braces enclosing a list of statements. PHP will execute these statements only when the answer to the question in the parentheses is yes. After completing these statements, it will continue after the braces. But if the answer is no, PHP will skip over the statements inside the braces (without executing them) and immediately go on to the first statement following the braces.
One thing you should be careful of: An if statement does not involve any semicolons. A typical beginner's mistake is to write something like if($a > $b); {, with a semicolon inserted between the close parenthesis and the opening brace. Unfortunately, PHP allows this but interprets it very differently from what you will intend: If you insert a semicolon there, PHP will think you mean that the body of the if statement is the statement consisting of only a semicolon — a statement with nothing in it. The end result is that if $a exceeds $b, the computer will perform this empty statement (doing nothing) and then proceed into the braces; but if $a does not exceed $b, the computer will skip over the empty statement and proceed into the braces anyway.
In the above example, the three assignment statements in the braces end up swapping the values associated with $form_begin and $form_end: We first assigning $old_begin to refer to the original value of $form_begin; then we assign $form_begin to the original value of $form_end; and finally we assign $form_end to the value of $old_begin, which is the original value of $form_begin.

6.2. Booleans and conditions

The portion in parentheses is supposed to be a yes/no value. PHP has a special type for such values called the boolean. (This is the fourth type we've seen, on top of integers, floating-point values, and strings.) There are only two different boolean values, written TRUE and FALSE.
In fact, the expression in parentheses doesn't need to be a boolean. If it isn't, then PHP will first convert it to TRUE or FALSE to see whether to execute what in the braces. The rule it uses is that every integer, floating-point value, and string value is equivalent to TRUE except for the following, which are FALSE:
  • the integer 0
  • the floating-point value 0.0
  • the string with nothing in it ("")
  • the string containing just the 0 digit ("0")
Generally speaking, I recommend avoiding any dependence on these rules; instead, you would use an assignment operator to compare values.
PHP provides a number of operators for comparing values:
<less than
>greater than
<=less than or equal (i.e., at most)
>=greater than or equal (i.e., at least)
==equal
!=not equal
The usage of the exclamation point '!' for the word not is a bit odd, but it's not hard to grow accustomed to it.
Note, though, that the way to check whether two things are equal is to use two equals signs. PHP does this because a single equals sign is already being used in PHP to represent assigning a value to a number.
In fact, the single equals sign is actually an operator, too, whose value is whatever is assigned. This can lead to weird behavior. Suppose you write the following.
if($form_begin = $form_end) {                        // WRONG!
    echo "Error: The range doesn't contain any numbers.";
}
In the parentheses, we use a single equals sign, and so PHP takes this to mean that we actually wish to change $form_begin so that its value is the same as $form_end's value. Moreover, the value of the expression in the parentheses is this assigned value, which PHP will interprets as TRUE unless $form_end happened to be the empty string or the string 0. So in fact the program will probably execute what is in the braces, reporting the error. And then of course it will go on and do whatever follows the braces… but now $form_begin and $form_end will represent the same value.
Needless to say, this is a fairly big error in our program. Beginning PHP programmers are almost guaranteed to encounter it, and it can be hard to see if you don't know about this distinction: A single equals means to change a variable; a double equals means to compare two values to see whether they are equal.
With experience, you can avoid the problem by following one simple rule: Inside parentheses on an if, you should never use a single equals sign. And in assignment statements, ou should always use a single equals sign.

6.3. else and elseif clauses

Sometimes you want one thing to happen in one case but a very different thing to happen in other cases. For these, PHP provides an option of including an else clause following the body of an if.
if($form_begin != $form_end) {
    $choice = rand($form_begin, $form_end);
    echo "I have selected $choice from the range.";
else {
    echo "The range includes only one choice: $form_begin.";
}
It also sometimes happens that there are several cases. For these, you can include an elseif clause, optionally followed by an else clause. An elseif clause contains an additional condition in parentheses, followed by the set of statements to execute in that case if the condition turns out to be true.
if($form_begin < $form_end) {
    $choice = rand($form_begin, $form_end);
    echo "I have selected $choice from the range.";
elseif($form_begin > $form_end) {
    $choice = rand($form_end, $form_begin);
    echo "I have selected $choice from the inverted range.";
else {
    echo "The range includes only one choice: $form_begin.";
}
You can have have any number of elseif clauses in the same if statement; but the else clause, if there is one, must come last among them.
In executing an if statement with elseif clauses, PHP will consider each clause's condition in sequence, until it finds one that is true; then it will skip over all other clauses. Looked at another way: The computer will check an elseif clause only when the initial if condition and any preceding elseif conditions all turn out to fail. The body of the else will be executed only when the if and all elseif conditions fail.
The following illustrates this. Note that if $grade were 85, it would display only that a B was received (even though later elseif clauses also seemingly apply), since PHP doesn't consider later elseif clauses in the same statement once it finds one that applies.
if($grade >= 90) {
    echo "You aced the course.";
elseif($grade >= 80) {
    echo "You received a B.";
elseif($grade >= 70) {
    echo "You received a C.";
else {
    echo "You failed.";
}

6.4. A note on indentation

You've probably noticed that the above examples are very systematic about how they are indented. In fact, PHP doesn't care about indentation, and you could just as easily place the entire program on the same line.
if($grade>=90){echo "You aced the course.";}elseif($grade>=80){echo
"You received a B.";}elseif($grade>=70){echo"You received a C.";}else
{echo "You failed.";}
However, code written in this way is very difficult to repair when there is a problem with it, and for those who haven't just typed it, it is fairly difficult to read. For these two reasons, you should follow a similar convention, where inside each set of braces, you indent each line`a bit further than where the if statement starts, so that it's easy to see where the body is.
You'll also notice that I'm very systematic about how I place the braces: An opening brace is usually put off at the end of a line, and the corresponding closing brace is placed at the start of the line where it appears, indented just as far as the initial if. This convention isn't quite as strong as the convention about indentation, but arranging the braces in some sort of system is very well-established among programmers — and the particular technique that I'm illustrating is the most popular system that experienced programmers use. You should follow some well-established system of indenting code and dealing with braces.

Labels

AJAX (1) Answers (1) Apache (1) Array (16) bug (1) C (1) C++ (1) Calendar (1) Class (1) Commands (1) Cookies (2) Database (2) Date (7) Days (1) explode (1) File Upload (1) FILES (1) firewall (1) fix (1) Functions (26) GET (1) GMT (1) JavaScript (2) localhost (1) Mail (1) Menu (1) MYSQL (13) PERL (1) PHP (36) php.ini (1) POST (1) preg_match (1) Questions (1) Script (1) SMS (2) Solution (1) String (1) Time (5) Time Zone (1) Vista (1) Wamp Server (1) windows 7 (2) XML (1)

Popular Posts

Popular Posts