PHP & MYSQL Unit-3
PHP & MYSQL Unit-3
PHP & MYSQL Unit-3
An array is a data structure that stores one or more data values having some relation among them, in a
single variable. For example, if you want to store the marks of 10 students in a class, then instead of
defining 10 different variables, it’s easy to define an array of 10 length.
Arrays in PHP behave a little differently than the arrays in C, as PHP is a dynamically typed language as
against C which is a statically type language.
There are two ways to declare an array in PHP. One is to use the built-in array() function, and the other is
to use a shorter syntax where the array elements are put inside square brackets.
Each value in the parenthesis may be either a singular value (it may be a number, string, any object or
even another array), or a key-value pair. The association between the key and its value is denoted by the
"=>" symbol.
Examples
$arr1 = array (10, ”asd”, 1.55, true);
$arr2 = array (“one”=>1, “two”=>2, “three”=>3);
$arr3 = array (
array(10, 20, 30),
array(“ten”, “twenty”, “thirty”),
array(“physics”=>70, “chemistry”=>80, “maths”=>60)
);
Indexed Array − An array which is a collection of values only is called an indexed array. Each
value is identified by a positional index staring from "0". Values are stored and accessed in linear
fashion.
Associative Array − If the array is a collection of key-value pairs, it is called as an associative
array. The key component of the pair can be a number or a string, whereas the value part can be
of any type. Associative arrays store the element values in association with key values rather than
in a strict linear index order.
Multi Dimensional Array − If each value in either an indexed array or an associative array is an
array itself, it is called a multi dimensional array. Values are accessed using multiple indices
NOTE − Built-in array functions is given in function reference PHP Array Functions
It may be noted that PHP internally considers any of the above types as an associative array itself. In case
of an indexed array, where each value has index, the index itself is its key. The var_dump() function
reveals this fact.
Example
In this example, arr1 is an indexed array. However, var_dump()which displays the structured information
of any object, shows that each value is having its index as its key.
<?php
$arr1 = [10, "asd", 1.55, true];
var_dump($arr1);
?>
array(4) {
[0]=>
int(10)
[1]=>
string(3) "asd"
[2]=>
float(1.55)
[3]=>
bool(true)
}
Example
The same principle applies to a multi-dimensional index array, where each value in an array is another
array.
<?php
$arr1 = [
[10, 20, 30],
["Ten", "Twenty", "Thirty"],
[1.1, 2.2, 3.3]
];
var_dump($arr1);
?>
array(3) {
[0]=>
array(3) {
[0]=>
int(10)
[1]=>
int(20)
[2]=>
int(30)
}
[1]=>
array(3) {
[0]=>
string(3) "Ten"
[1]=>
string(6) "Twenty"
[2]=>
string(6) "Thirty"
}
[2]=>
array(3) {
[0]=>
float(1.1)
[1]=>
float(2.2)
[2]=>
float(3.3)
}
}
Example
For an indexed array, put the index inside the square bracket, as the index itself is anyway the key.
<?php
$arr1 = [10, 20, 30];
$arr2 = array("one"=>1, "two"=>2, "three"=>3);
var_dump($arr1[1]);
var_dump($arr2["two"]);
?>
int(20)
int(2)
Numerically Indexed Arrays
Let’s assume that you’ve been tasked with creating a simple website for a local officesupply company and
you’re currently working on the section devoted to paper. One way to manage the various items of stock
in this category would be to place them in a numeric array. You can see the simplest way of doing so in
Example 6-1.
output
Associative Arrays
Keeping track of array elements by index works just fine, but can require extra work in terms of
remembering which number refers to which product. It can also make code hard for other programmers to
follow.
This is where associative arrays come into their own. Using them, you can reference the items in an array
by name rather than by number. Example 6-4 expands on the previous code by giving each element in the
array an identifying name and a longer, more explanatory string value.
In place of a number (which doesn’t convey any useful information, aside from the position of the item in
the array), each item now has a unique name that you can use to reference it elsewhere, as with the echo
statement—which simply prints out Laser Printer. The names (copier, inkjet, and so on) are called indexes
or keys, and the items assigned to them (such as Laser Printer) are called values.
This very powerful feature of PHP is often used when you are extracting information from XML and
HTML. For example, an HTML parser such as those used by a search engine could place all the elements
of a web page into an associative array whose names reflect the page’s structure:
$html['title'] = "My web page";
$html['body'] = "... body of web page ...";
The program would also probably break down all the links found within a page into another array, and all
the headings and subheadings into another. When you use associative rather than numeric arrays, the code
to refer to all of these items is easy to write and debug.
The first half of this snippet assigns the old, shortened product descriptions to the array $p1. There are
four items, so they will occupy slots 0 through 3. Therefore, the echo statement prints out the following:
p1 element: Laser
The second half assigns associative identifiers and accompanying longer product descriptions to the array
$p2 using the format index => value. The use of => is similar to the regular = assignment operator, except
that you are assigning a value to an index and not to a variable. The index is then inextricably linked with
that value, unless it is assigned a new value. The echo command therefore prints out this:
p2 element: Inkjet Printer
You can verify that $p1 and $p2 are different types of array, because both of the fol‐ lowing commands,
when appended to the code, will cause an Undefined index or Undefined offset error, as the array
identifier for each is incorrect:
echo $p1['inkjet']; // Undefined index
echo $p2[3]; // Undefined offset
Remember that associative arrays do not require numeric indexes, so the variable $j is not used in this
example. Instead, each item of the array $paper is fed into the key/ value pair of variables $item and
$description, from which they are printed out. The displayed result of this code is as follows:
copier: Copier & Multipurpose
inkjet: Inkjet Printer
laser: Laser Printer
photo: Photographic Paper
Multidimensional Arrays
A simple design feature in PHP’s array syntax makes it possible to create arrays of more than one
dimension. In fact, they can be as many dimensions as you like (although it’s a rare application that goes
further than three).
That feature is the ability to include an entire array as a part of another one, and to be able to keep doing
so, just like the old rhyme: “Big fleas have little fleas upon their backs to bite ’em. Little fleas have lesser
fleas, add flea, ad infinitum.”
Let’s look at how this works by taking the associative array in the previous example and extending it; see
Example 6-10.
Output
is_array
Arrays and variables share the same namespace. This means that you cannot have a string variable called
$fred and an array also called $fred. If you’re in doubt and your code needs to check whether a variable is
an array, you can use the is_array function, like this:
echo (is_array($fred)) ? "Is an array" : "Is not an array";
Note that if $fred has not yet been assigned a value, an Undefined variable message will be generated.
count
Although the each function and foreach...as loop structure are excellent ways to walk through an array’s
contents, sometimes you need to know exactly how many ele‐ ments there are in your array, particularly
if you will be referencing them directly. To count all the elements in the top level of an array, use a
command such as this:
echo count($fred);
Should you wish to know how many elements there are altogether in a multidimen‐sional array, you can
use a statement such as the following:
The second parameter is optional and sets the mode to use. It should be either a 0 to limit counting to only
the top level, or 1 to force recursive counting of all subarray elements too
sort
Sorting is so common that PHP provides a built-in function. In its simplest form, you would use it like
this:
sort($fred);
Unlike some other functions, sort will act directly on the supplied array rather than returning a new array
of sorted elements. Instead, it returns TRUE on success and FALSE on error and also supports a few
flags, but the main two that you might wish to use force sorting to be made either numerically or as
strings, like this:
sort($fred, SORT_NUMERIC);
sort($fred, SORT_STRING);
You can also sort an array in reverse order using the rsort function, like this:
rsort($fred, SORT_NUMERIC);
rsort($fred, SORT_STRING);
shuffle
There may be times when you need the elements of an array to be put in random order, such as when
you’re creating a game of playing cards:
shuffle($cards);
Like sort, shuffle acts directly on the supplied array and returns TRUE on success or FALSE on error.
explode
This is a very useful function with which you can take a string containing several items separated by a
single character (or string of characters) and then place each of these items into an array. One handy
example is to split up a sentence into an array containing all its words, as in Example 6-12.
This example prints out the following (on a single line when viewed in a browser):
Array ( [0] => This
[1] => is
[2] => a
[3] => sentence
[4] => with
[5] => seven
[6] => words )
The first parameter, the delimiter, need not be a space or even a single character. Example 6-13 shows a
slight variation.
reset
When the foreach...as construct or the each function walks through an array, it keeps an internal PHP
pointer that makes a note of which element of the array it should return next. If your code ever needs to
return to the start of an array, you can issue reset, which also returns the value of that element. Examples
of how to use this function are as follows:
end
As with reset, you can move PHP’s internal array pointer to the final element in an array using the end
function, which also returns the value of the element, and can be used as in these examples:
end($fred);
$item = end($fred);
This chapter concludes your basic introduction to PHP, and you should now be able to write quite
complex programs using the skills you have learned. In the next chap‐ ter, we’ll look at using PHP for
common, practical tasks.
Compact
At times you may want to use compact, the inverse of extract, to create an array from variables and their
values. Example 6-14 shows how you might use this func‐tion.
Extract
Sometimes it can be convenient to turn the key/value pairs from an array into PHP variables. One such
time might be when you are processing the $_GET or $_POST vari‐ ables as sent to a PHP script by a
form.
When a form is submitted over the Web, the web server unpacks the variables into a global array for the
PHP script. If the variables were sent using the Get method, they will be placed in an associative array
called $_GET; if they were sent using Post, they will be placed in an associative array called $_POST.
You could, of course, walk through such associative arrays in the manner shown in the examples so far.
However, sometimes you just want to store the values sent into variables for later use. In this case, you
can have PHP do the job automatically:
extract($_GET);
So, if the query string parameter q is sent to a PHP script along with the associated value Hi there, a new
variable called $q will be created and assigned that value.
Be careful with this approach, though, because if any extracted variables conflict with ones that you have
already defined, your existing values will be overwritten. To avoid this possibility, you can use one of the
many additional parameters available to this function, like this:
1. include
2. require
Include Statement
The ‘include’ or ‘require’ statement can be used to insert the content of one PHP file into another
PHP file (before the server executes it). Except in the case of failure, the ‘include’ and ‘require
statements’ are identical:
● Include in PHP will only generate an alert (E_WARNING), and the script will
proceed.
● Require will produce a fatal error (E_COMPILE_ERROR) and interrupt the script.
If the include statement appears, execution should continue and show users the output even if the
include file is missing. Otherwise, always use the required declaration to include the main file in
the flow of execution while coding Framework, CMS, or a complex PHP program. This will help
prevent the application's protection and reputation from being jeopardized if one key file is
corrupted.
The include() function copies all of the text from a given file into the file that uses the include
function. It produces an alert if there is a problem loading a file; however, the script will still run.
PHP Include
Include is a keyword to include one PHP file into another PHP file. While including the content
of the included file will be displayed in the main file. The below example code will demonstrate
the concept of PHP include.
Syntax:
include 'file_name';
or
require 'file_name';
Code:
Page1.php
<?php
?>
Main.php
<html>
<body>
</body>
</html>
Explanation:
In the above code, there are two files, that is, Page1.php and Main.php. In the Main.php file, the
Page1.php has been included with the help of line <?php include ‘Page1.php’;?>
Output:
PHP Require
The PHP require function is similar to the include function, which is used to include files. The
only difference is that if the file is not found, it prevents the script from running, while include
does not.
The require() function copies all of the text from a given file into the file that uses the include
function. The require() function produces a fatal error and stops the script's execution if there is a
problem loading a file. So, apart from how they treat error conditions, require() and include() are
identical. Since scripts do not execute if files are missing or misnamed, the require() function is
recommended over include().
Syntax:
require 'file_name';
Or
require ('file_name');
Code:
Menu1.html:
<html>
<body>
<ahref="http://www.google.com">Google</a> |
<ahref="http://www.yahoo.com">Yahoo</a> |
<ahref="http://www.maps.com">Maps</a> |
<ahref="http://www.tutorial.com">Tutorial</a>
</body>
</html>
Main.html:
<html>
<body>
<h1>welcome</h1>
</body>
</html>
Output:
include() Vs require()
In most cases, the require() statement works in the same way as the include() statement. The only
difference is that the include() statement generates a PHP alert but allows script execution to
proceed if the file to be included cannot be found. At the same time, the require() statement
generates a fatal error and terminates the script.
he term "Type Casting" refers to conversion of one type of data to another. Since PHP is a
weakly typed language, the parser coerces certain data types into others while performing certain
operations. For example, a string having digits is converted to integer if it is one of the operands
involved in the addition operation.
<?php
$a = 10;
$b = '20';
$c = $a+$b;
echo "c = " . $c;
?>
In this case, $b is a string variable, cast into an integer to enable addition. It will produce the
following output −
c = 30
Let's take another example. Here, an integer variable $a is converted to a string so that it is
concatenated with a string variable.
<?php
$a = 10;
$b = '20';
$c = $a.$b;
echo "c = " . $c;
?>
c = 1020
In addition to such coercive type conversion, there are other ways to explicitly cast one type of
data to other. You can use PHP’s type casting operators or type casting functions for this purpose.
$var = (type)expr;
Casting to Integer
You can easily convert a float value to an integer. Take a look at the following example −
<?php
$a = 9.99;
$b = (int)$a;
var_dump($b);
?>
int(9)
Note that the float value is not rounded to the nearest integer; instead it just returns the integer
part.
<?php
$a = "99";
$b = (int)$a;
var_dump($b);
?>
int(99)
PHP has a built-in mail() function to send an email. However, you need configure properly the "php.ini"
settings to be able to do so. First, you must know the SMTP domain of the web hosting platform that you
are using. For example, if your website is being hosted on GoDaddy hosting service, the SMTP domain is
"smtp.secureserver.net", which you should use in the configuration.
If you use Windows based hosting of GoDaddy, you should ensure that two directives are enabled in
php.ini file. The first is called SMTP that defines your email server address. The second is called
sendmail_from which defines your own email address.
[mail function]
; For Win32 only.
SMTP = smtp.secureserver.net
Linux users simply need to let PHP know the location of their sendmail application. The path and any
desired switches should be specified to the sendmail_path directive.
[mail function]
; For Win32 only.
SMTP =
mail() function in PHP requires three mandatory arguments that specify the recipient's email address,
the subject of the message and the actual message additionally there are other two optional parameters.
Syntax:
Parameters
to − Required. Specifies the receiver / receivers of the email
subject − Required. Specifies the subject of the email. This parameter cannot contain any newline
characters
message − Required. Defines the message to be sent. Each line should be separated with a LF
(\n). Lines should not exceed 70 characters
headers − Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers
should be separated with a CRLF (\r\n)
parameters − Optional. Specifies an additional parameter to the send mail program
Multiple recipients can be specified as the first argument to the mail() function in a comma separated
list.
While sending an email message you can specify a Mime version, content type and character set to send
an HTML email.
Example
The following example shows how to send an HTML email message to "xyz@somedomain.com" copying
it to "afgh@somedomain.com". You can code this program in such a way that it should receive all content
from the user and then it should send an email.
It should receive all content from the user and then it should send an email.
<?php
$to = "xyz@somedomain.com";
$subject = "This is subject";
● $GLOBALS
● $_SERVER
● $_REQUEST
● $_POST
● $_GET
● $_FILES
● $_ENV
● $_COOKIE
● $_SESSION
The PHP superglobals $_GET and $_POST are used to collect form-data.
<html>
<body>
</body>
</html>
When the user fills out the form above and clicks the submit button, the form data is sent for
processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables.
<html>
<body>
</body>
</html>
Welcome John
Your email address is john.doe@example.com
The same result could also be achieved using the HTTP GET method:
</body>
</html>
<html>
<body>
</body>
</html>
The code above is quite simple, and it does not include any validation.
You need to validate form data to protect your script from malicious code.
Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that
they are always accessible, regardless of scope - and you can access them from any function, class or
file without having to do anything special.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
Note: GET should NEVER be used for sending passwords or other sensitive information!
Moreover POST supports advanced functionality such as support for multi-part binary input while
uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.