SlideShare a Scribd company logo
1 of 130
1
C-DAC,Bytes
NewDelhi
Introduction to PHPIntroduction to PHP
Prabhat Jonathan
2
What is PHP?
 PHP stands for PHP: Hypertext Preprocessor
 PHP is a server-side scripting language, like
ASP
 PHP scripts are executed on the server
 PHP supports many databases (MySQL,
Informix, Oracle, Sybase, Solid, PostgreSQL,
Generic ODBC, etc.)
 PHP is an open source software
 PHP is free to download and use
 PHP is an interpreted language.
3
What is a PHP File?
PHP files can contain text, HTML
tags and scripts
PHP files are returned to the
browser as plain HTML 
PHP files have a file extension of
".php", ".php3", or ".phtml"
4
Why PHP?
 PHP runs on different platforms
(Windows, Linux, Unix, etc.)
 PHP is compatible with almost all
servers used today (Apache, IIS, etc.)
 PHP is FREE to download from the
official PHP resource: www.php.net
 PHP is easy to learn and runs
efficiently on the server side
 PHP is an open-source projec
5
A PHP Request
6
PHP: Development environment
must contain at least three
components:
 A base operating system (OS) and server
environment (usually Linux)
 A Web server (usually Apache on Linux or IIS on
Windows) to intercept HTTP requests and either
serve them directly or pass them on to the PHP
interpreter for execution
 A PHP interpreter to parse and execute PHP code,
and return the results to the Web server
There’s also often a fourth optional but very
useful component:
 A database engine (such as MySQL) that holds
application data, accepts connections from the PHP
layer, and modifies or retrieves data from the
database
7
PHP Syntax
A PHP scripting block always
starts with <?php and ends with ?
>. A PHP scripting block can be
placed anywhere in the
document.
<?php
// this line of code displays a famous quotation
echo ‘Love Can Make Any One Poet!';
?>
8
Comments in PHP
Single-line comments must be
preceded by the // characters
multiline comments must be enclosed
within a /* ... */ comment block
9
Mixing PHP with HTML
<html>
<body>
<?php
echo "Hello World";
?>
</body>
</html>
10
PHP Variables
A variable is simply a container that’s
used to store both numeric and non-
numeric information
Every variable name must be preceded
with a dollar ($) symbol and must begin
with a letter or underscore character
So, for example, $root, $_num, and
$query2
11
Assigning Values to Variables
Assigning a value to a variable in PHP
is quite easy: use the equality (=)
symbol, which also happens to be
PHP’s assignment operator.
<?php
// assign value to variable
$name = ‘Prabhat’;
?>
<h2>
Welcome to <?php echo $name; ?>'s Blog!
</h2>
12
Destroying Variables
<?php
// assign value to variable
$car = 'Porsche';
// print variable value
// output: 'Before unset(), my car is a Porsche'
echo "Before unset(), my car is a $car";
// destroy variable
unset($car);
// print variable value
// this will generate an 'undefined variable' error
// output: 'After unset(), my car is a '
echo "After unset(), my car is a $car";
?>
13
PHP Operators
14
Arithmetic Operators
15
Assignment Operators
= operator is Assignment
Operator
16
Comparison Operators
17
Logical Operators
18
The if Statement
if (condition) code to be executed if
condition is true;
<?php
// if number is less than zero
// print message
$number = -88;
if ($number < 0) {
echo 'That number is negative';
}
?>
19
The If...Else Statement
if (condition)
code to be executed if condition is
true;
else
code to be executed if condition is
false;
20
<?php
// change message depending on whether
// number is less than zero or not
$number = -88;
if ($number < 0) {
echo 'That number is negative';
} else {
echo 'That number is either positive or zero';
}
?>
21
The if-elseif-else Statement<?php
// handle multiple possibilities
// define a different message for each day
$today = 'Tuesday';
if ($today == 'Monday') {
echo 'Monday's child is fair of face.';
} elseif ($today == 'Tuesday') {
echo 'Tuesday's child is full of grace.';
} elseif ($today == 'Wednesday') {
echo 'Wednesday's child is full of woe.';
} elseif ($today == 'Thursday') {
echo 'Thursday's child has far to go.';
} elseif ($today == 'Friday') {
echo 'Friday's child is loving and giving.';
} elseif ($today == 'Saturday') {
echo 'Saturday's child works hard for a living.';
} else {
echo 'No information available for that day';
}
?>
22
The switch-case Statement<?php
// handle multiple possibilities
// define a different message for each day
$today = 'Tuesday';
switch ($today) {
case 'Monday':
echo 'Monday's child is fair of face.';
break;
case 'Tuesday':
echo 'Tuesday's child is full of grace.';
break;
case 'Wednesday':
echo 'Wednesday's child is full of woe.';
break;
case 'Thursday':
echo 'Thursday's child has far to go.';
break;
case 'Friday':
echo 'Friday's child is loving and giving.';
break;
case 'Saturday':
echo 'Saturday's child works hard for a living.';
break;
default:
echo 'No information available for that day';
break;
}
?>
23
Repeating Actions with Loops
24
The while Statement
Syntax
while (condition)
code to be executed;
<?php
// repeat continuously until counter becomes 10
// output: 'xxxxxxxxx'
$counter = 1;
while ($counter < 10) {
echo 'x';
$counter++;
}
?>
25
The do-while Loop
Syntax
do
{
code to be executed;
} while (condition);
26
<?php
// repeat continuously until counter becomes 10
// output: 'xxxxxxxxx'
$counter = 1;
do {
echo 'x';
$counter++;
} while ($counter < 10);
?>
27
The for Loop
 Syntax
for (init; cond; incr)
{
code to be executed;
}
 init: Is mostly used to set a counter, but can be any code to be
executed once at the beginning of the loop statement.
 cond: Is evaluated at beginning of each loop iteration. If the
condition evaluates to TRUE, the loop continues and the code
executes. If it evaluates to FALSE, the execution of the loop
ends.
 incr: Is mostly used to increment a counter, but can be any
code to be executed at the end of each loop.
28
<?php
// repeat continuously until counter becomes 10
// output:
for ($x=1; $x<10; $x++) {
echo "$x ";
}
?>
29
PHP Functions
30
Create a PHP Function
 All functions start with the word "function()"
 Name the function - It should be possible to
understand what the function does by its
name. The name can start with a letter or
underscore (not a number)
 Add a "{"  - The function code starts after the
opening curly brace
 Insert the function code
 Add a "}"  - The function is finished by a
closing curly brace
31
<?php
function nme()
{
echo "Kya hal hae DAC !";
}
nme();
?>
32
PHP Arrays
 An array can store one or more values
in a single variable name.
 There are three different kind of
arrays:
Numeric array - An array with a numeric
ID key
Associative array - An array where each
ID key is associated with a value
Multidimensional array - An array
containing one or more arrays
33
Numeric Arrays
A numeric array stores each
element with a numeric ID key.
$names = array("Prabhat",“Nitesh",“shudhanshu");
34
<? Php
$names[0] = “Arvind";
$names[1] = “Nitesh";
$names[2] = “shudhanshu";
echo $names[1] . " and " . $names[2] . " are ". $names[0] .
C-DAC Students ";
?>
35
Associative Arrays
<?php
// define array
$fruits = array('apple', 'banana', 'pineapple', 'grape');
?>
36
The keys of the array must be unique<?php
// define array
$fruits = array(
'a' => 'apple',
'b' => 'banana',
'p' => 'pineapple',
'g' => 'grape‘
Echo “$fruit[“a”] is gud friut”
);
?>
37
Multidimensional Arrays
 onion, 0.50
 apple, 2.50
 orange, 2.00
 chicken, 3.50
 potato, 1.00
 Fish,5.00
38
$foodPrices[‘onion’] = 0.50;
$foodPrices[‘apple’] = 2.50;
$foodPrices[‘orange’] = 2.00;
$foodPrices[‘chicken’] = 3.50;
$foodPrices[‘potato’] = 1.00;
$foodPrices[‘fish’] = 5.00;
39
 $foodPrices [‘vegetable’] [‘onion’] = 0.50;
 $foodPrices [‘vegetable’] [‘potato’] = 1.00;
 $foodPrices [‘fruit’] [‘apple’] = 2.50;
 $foodPrices [‘fruit’] [‘orange’] = 2.00;
 $foodPrices [‘meat’] [‘chicken’] = 3.50;
 $foodPrices [‘meat’] [‘fish’] = 5.00;
40
$foodPrices key value
vegetable onion
Potato
0.50
1.00
fruit orange
apple
2.00
2.50
meat chicken
Fish
3.50
5.00
41
$foodPrices = array(
“vegetable”=>
array(“potato”=>1.00,
”onion”=>.50),
“fruit”=>
array(“apple”=>2.50,
”orange”=>2.00)
);
42
Using multidimensional
arrays in statements
 $fishPrice = $foodPrices[‘meat’][‘fish’];
 echo “The price of fish is Rs .” $fishprice ;
43
Sorting an Array in PHP
sort(), to sort an array in
ascending order
44
<?php
$narray[0]="Alfred";
$narray[1]="Robert";
$narray[2]="Deepak";
$narray[3]="Teresa";
$narray[4]="Joshua";
$narray[5]="Chandni";
$narray[6]="Sadiq";
$narray[7]="Vladimir";
for($i=0; $i<8; $i++)
{
print $narray[$i] . "<br />";
}
?>
45
 The output of this PHP code is:
Alfred
Robert
Deepak
Teresa
Joshua
Chandni
Sadiq
Vladimir
46
sort($narray);
for($i=0; $i<8; $i++)
{
print $narray[$i] . "<br />";
}
47
Alfred
Chandni
Deepak
Joshua
Robert
Sadiq
Teresa
Vladimir
48
rsort($narray);
for($i=0; $i<8; $i++)
{
print $narray[$i] . "<br />";
}
49
 Now the output is:
Vladimir
Teresa
Sadiq
Robert
Joshua
Deepak
Chandni
Alfred
50
PHP Cookies
 Users may set their browsers to refuse
cookies
 If your application depends on cookies, it won’t run if
cookies are turned off.
 PHP has features that work better than
cookies.
 PHP 5, PHP sessions can store information that is
available for the entire session
 You can store data in a database.
 Users can’t delete the data in your database
unexpectedly.
51
Setting Cookies with PHP:
 PHP provided setcookie() function to set a cookie.
 Name - This sets the variable name of the cookie and is
stored in an environment variable called $_COOKIE or
$HTTP_COOKIE_VARS variables. This variable is used
while accessing cookies.
 Value -This sets the value of the named variable and is the
content that you actually want to store.
 Expiry - This specify a future time in seconds since
00:00:00 GMT on 1st Jan 1970. After this time cookie will
become inaccessible. If this parameter is not set then
cookie will automatically expire when the Web Browser is
closed.
Setcookie (variable_name, value, expire);
52
setcookie(“state”,”UP”);
echo “Your home state is “.
$_COOKIE[“state”];
or
echo “Your home state is “. .
$HTTP_COOKIE_VARS [“state”];
Your home state is UP
53
Setting expiration dates
 The expiretime value sets the time when the
cookie expires.
 time: This function returns the current time in a
format the computer can understand.
 You use the time function plus a number of seconds to set the
expiration time of the cookie
 setcookie(“state”,”UP”,time()+3600);
//expires in one hour
 setcookie(“Name”,$Name,time()
+(3*86400))//expires 3 days
54
mktime: This function returns a date and time in a
format that the computer can understand. You must
provide the desired date and time in the following
order: hour, minute, second, month, day, and year
 setcookie(“state”,”CA”,mktime(3,0,0,4,1,2009));
//Expires at 3:00 AM on April 1, 2009
 setcookie(“state”,”CA”,mktime(13,0,0,,,));
//expires at 1:00 PM today
55
isset()
isset() function to check if a
cookie is set or not.
56
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br
/>";
else echo "Sorry... Not recognized" . "<br />";
?>
</body>
</html>
57
PHP Sessions
A session is the time that a user spends
at your Web site
A session creates a file in a temporary
directory on the server where registered
session variables and their values are
stored. This data will be available to all
pages on the site during that visit.
58
 To make session information available, PHP does the
following:
1. PHP assigns a session ID number.
2. PHP stores the variables that you want saved for the session in a file
on the server
3. PHP passes the session ID number to every page.
4. PHP gets the variables from the session file for each new session
page
 The variables are available in the $_SESSION array.
5. A session ends when the user loses the browser or after
leaving the site, the server will terminate the session after a
predetermined period of time, commonly 30 minutes duration
59
Opening and closing sessions
Open the session with the session_start
function, as follows:
session_start();
The function first checks for an existing
session ID number. If it finds one, it sets
up the session variables. If it doesn’t
find one, it starts a new session by
creating a new session ID number.
60
Storing a Session
Variable
To save a variable in a session so that
it’s available on later Web pages, store
the value in the $_SESSION array, as
follows:
$_SESSION[‘varname’] = “Prabhat”;
61
Destroying a Session
 If you wish to delete some session
data, you can use the unset() or the
session_destroy() function
 session_destroy() will reset your
session and you will lose all your
stored session data. This function
does not need any argument
 unset() function to unset a session
variable. its need argument
62
session_destroy()
<?php
session_destroy();
?>
63
unset()
<?php
unset($_SESSION['counter']);
?>
64
Using a form to upload a file
You can display a form that allows a
user to upload a file by using an HTML
form designed for that purpose. The
general format of the form is as follows:
65
 The enctype attribute is used in the form tag.
You must set this attribute to multipart/form-data
when uploading a file to ensure the file arrives
correctly.
 A hidden field is included that sends a value
(in bytes) for MAX_FILE_SIZE. If the user tries
to upload a file that is larger than this value, it won’t
upload. When sending the value for MAX_FILE_SIZE
in your form, you need to consider two size settings
in php.ini
 The input field that uploads the file is of type
file.
66
Note: The value for MAX_FILE_SIZE
must be sent before the file is uploaded
if you want the file size limit to apply to
the uploading file.
If you don’t like the location of the
temporary directory, you can change it
by changing upload_tmp_dir in the
php.ini file.
67
Accessing information about
an uploaded file
 Along with the file, information about the file is sent
with the form. This information is stored in the PHP
built-in array called $_FILES.
 $_FILES["fieldname"]["name"] - the name of the uploaded
file
 $_FILES["fieldname"]["type"] - the type of the uploaded file
 $_FILES["fieldname"]["size"] - the size in bytes of the
uploaded file
 $_FILES["fieldname"]["tmp_name"] - the name of the
temporary copy of the file stored on the server
 $_FILES["fieldname"]["error"] - the error code resulting from
the file upload
68
For Example
 suppose you use the following field to upload
a file:
<input type=”file” name=”user_file”>
 If the user uploads a file named test.txt by
using the form
$_FILES[user_file][name] = test.txt
$_FILES[user_file][type] = text/plain
$_FILES[user_file][tmp_name] =
D:WINNTphp92C.tmp
$_FILES[user_file][size] = 435
69
Moving uploaded files to their
destination
The general format of the statement
that moves the file is as follows:
move_uploaded_file(path/tempfilename,pat
h/permfilename);
tempfilename:
element in $_FILES stores the temporary filename
and location
move_uploaded_file($_FILES[‘user_file’
][‘tmp_name’],‘c:datanew_file.txt’);
70
Storing Data with PHP
 Many applications require the long-term
storage of information.
 The information needs to be stored on the
server
 Information can be stored on the server in flat
files or in databases.
 Flat files
are text files stored in the computer file system.
 Database
for data storage requires you to install and learn to use
database software, such as MySQL or Oracle.
71
Using Flat Files
Using a flat file requires three steps:
1. Open the file.
2. Write data into the file or retrieve data from the file.
3. Close the file.
72
Accessing files
$fh = fopen(“filename”,”mode”)
The variable, $fh, referred to as a file
handle
73
The filename can be a simple filename
(filename.txt), a path to the file
(c:/data/filename.txt), or a URL
(http://yoursite.com/filename.txt)
74
Opening files in read mode
$fh = fopen(“file1.txt”,”r”);
If the file can’t be found, a warning
message
Warning: fopen(file1.txt): failed to open
stream: No such file or directory in
d:test2.php on line 12
Remember, a warning condition does not stop the
script. The script continues to run, but the file doesn’t
open, so any later statements that read orwrite to the
file aren’t executed.
75
a die statement
$fh = fopen(“file1.txt”,”r”)
or die(“Can’t open file”);
76
Opening files in write mode
$fh = fopen(“c:/testdir/file1.txt”,”w”);
You can check whether a directory
exists before you try to write a file into it
by using the following statements:
If(is_dir(“c:/tester”))
{
$fh = fopen(“c:/testdir/file1.txt”,”w”);
}
77
Closing a file
To close a file after you have finished
reading or writing it, use the following
statement:
fclose($fh);
78
Writing to a file
 After you open the file, you can write into it by using
the fwrite statement, which has the following general
format:
fwrite($fh,datatosave);
79
For example,
$today = date(“Y-m-d”);
$fh = fopen(“file2.txt”,”a”);
fwrite($fh,$today);
fclose($fh);
Note:-for data in separate line use
fwrite($fh,$today”n”);
80
Reading from a file
You can read from a file by using the
fgets statement, which has the following
general format:
$line = fgets($fh)
$fh holds the pointer to the open file
PHP recognizes the end of the file, and
provides a function feof to tell you when
you reach the end of the file.
81
while(!feof($fh))
{
$line = fgets($fh);
echo “$line;
}
82
Working with Databases
 There are a large number of database
management systems currently available,
some commercial and some free
 IBM DB2
 Informix
 Ingres
 Microsoft SQL Server (MS SQL)
 mSQL
 MySQL
 Oracle
 PostgreSQL
 Sybase
83
Choosing a RDBMS
Choosing a RDBMS depends on your
needs.
Cost
Features
Resources
Some RDBMSs require more resources, such as
disk space and memory, than others. Like oracle
84
Understanding Databases,
Records, and Primary Keys
85
Understanding SQL Statements
Data Definition Language (DDL)
DDL consists of statements that define
the structure and relationships of a
database and its tables. Typically, these
statements are used to create, delete,
and modify databases and tables;
specify field names and types; and set
indexes.
86
 ● Data Manipulation Language (DML)
DML statements are related to altering and
extracting data from a database. These
statements are used to add records to, and
delete records from, a database; perform
queries; retrieve table records matching one
or more user-specified criteria; and join tables
together using their common fields.
87
● Data Control Language (DCL)
DCL statements are used to define
access levels and security privileges for
a database. You would use these
statements to grant or deny user
privileges; assign roles; change
passwords; view permissions; and
create rule sets to protect access to
data.
88
89
Creating and Populating a
Database
Creating the Database
mysql> CREATE DATABASE music;
Query OK, 1 row affected (0.05 sec)
Next, select this newly database as the
default for all future commands with the
USE statement:
mysql> USE music;
Database changed
90
Adding Tables
mysql> CREATE TABLE artists (
-> artist_id INT(4) NOT NULL PRIMARY
KEY AUTO_INCREMENT,
-> artist_name VARCHAR (50) NOT
NULL,
-> artist_country CHAR (2) NOT NULL
-> );
Query OK, 0 rows affected (0.07 sec)
91
 The NOT NULL modifier ensures that the field cannot
accept a NULL value after each field definition
 The PRIMARY KEY modifier marks the
corresponding field as the table’s primary key.
 The AUTO_INCREMENT modifier, which is only
available for numeric fields, tells MySQL to
automatically generate a value for this field every
time a new record is inserted into the table, by
incrementing the previous value by 1.
92
MySQL Data Types
93
Adding Records
mysql> INSERT INTO artists (artist_id,
artist_name, artist_country)
-> VALUES ('1', 'Aerosmith', 'US');
Query OK, 1 row affected (0.00 sec)
94
Executing Queries
 SQL allows you to
search for records
matching specific
criteria using the
SELECT statement
mysql> SELECT
artist_id,
artist_name
FROM artists;
artist_id artist_name
1 Kishore
2 Rafi
3 Lata
3 rows in set (0.00 sec)
95
Using PHP with a database
Whichever database you’re using, the
steps to interact with a database are
similar:
1. Connect to the database.
2. Send an SQL query that contains
instructions for the database software.
3. If you retrieved data from the database,
process the data.
4. Close the connection to the database.
96
Connecting to the database
 Location:
 The database does not need to be on the same computer
where PHP is installed. Therefore, you need to tell the PHP
connect function the name of the computer where the
database is located (the hostname). You can supply either
a domain name (such as mycompany.com) or an IP
address (such as 172.17.204.2). If the database is on the
same computer as PHP, you can use localhost for the
hostname.
 Account name
 You must provide a valid account name that can be used
to access the database. The database administrator sets
this up. If you’re using a Web hosting company, you will be
given a valid account name.
97
Password:
You have to have a valid password to access the
database. The database administrator sets this up. If
you’re using a Web hosting company, you will be
given a valid password for your account.
Database name:
An RDBMS can create and maintain many
databases, so you need to tell it which database you
want to use.
98
$host = “localhost”;
$account = “admin”;
$password = “secret”;
$dbname = “music”;
99
The basic command
 mysql_connect($hos, $account, $password);
 The password is optional, depending on whether this
particular database user requires one (it’s a good
idea). If not, just leave that variable off.
100
mysqli function
mysqli_connect, which adds a fourth
parameter allowing you to select a
database in the same function you use
to connect.
 mysqli_connect($hos, $account, $password,
$dbname );
101
mysql_select_db
If you need it only if you want to use
multiple databases on the same
connection.
Next, you’ll want to choose a database
to work on:
mysql_select_db($database);
if you’re using variables; or
mysql_select_db(‘phpbook’);
if you’re using a literal string.
102
mysql_query()
A database query from PHP is basically
a MySQL command wrapped up in a
tiny PHP function called mysql_query().
This is where you use the basic SQL
workhorses of SELECT, INSERT,
UPDATE, and DELETE
103
mysql_query(“SELECT * FROM Product
WHERE ID<10”);
Or
$query = “SELECT * FROM Product WHERE
ID<10”;
$result = mysql_query($query);
104
Fetching Data Sets
 mysql_fetch_row:
Returns row as an enumerated array
 mysql_fetch_object:
Returns row as an object
 mysql_fetch_array:
 Returns row as an associative array
 mysql_result:
Returns one cell of data
105
mysql_fetch_row
$query = “SELECT ID, LastName, FirstName
FROM users WHERE Status = 1”;
$result = mysql_query($query);
while ($name_row = mysql_fetch_row($result)) {
print(“$name_row[0] $name_row[1]
$name_row[2]<BR>n”);
}
This code will output the specified rows from the database,
each line containing one row or
the information associated with a unique ID (if any).
106
mysql_fetch_object
 Function do the same task, except the row is
returned as an object rather than an array.
$query = “SELECT ID, LastName, FirstName
FROM users WHERE Status = 1”;
$result = mysql_query($query);
while ($row = mysql_fetch_object($result)) {
echo “$row->ID, $row->LastName, $row-
>FirstName<BR>n”;
}
107
mysql_fetch_array
 This function offers the choice of results as
an associative or an enumerated array or
both
$query = “SELECT ID, LastName, FirstName
FROM users WHERE Status = 1”;
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo “$row[‘ID’], $row[‘LastName’],
$row[‘FirstName’]<BR>n”;
}
108
Remember that mysql_fetch_array can
also be used exactly the same way as
mysql_fetch_row—with numerical
identifiers rather than field names.
109
Setting up PHP to send e-mail
 E-mail is sent by an outgoing e-mail server.
To send e-mail, you need access to an
outgoing server. If you can send e-mail from
your own computer right now, you’re using an
outgoing server.
 Your outgoing mail server is typically an
SMTP (Simple Mail Transfer Protocol) server.
Whether you use a LAN at work, a cable
modem at home, or an ISP via a modem, you
send your mail with an SMTP server, and the
server has an address that you need to know.
110
With the name of your outgoing mail
server in front of you, open php.ini
[mail function]
; For Win32 only.
SMTP = localhost
; For Win32 only.
;sendmail_from = me@localhost.com
111
 Windows users need to change the first two
settings. The first setting is where you put the
name of your outgoing server, as follows:
SMTP = mail.ispname.com
 The second setting is the return address that
is sent with all your e-mail. Change the
setting to the e-mail address you want to use
for your return address, as follows:
sendmail_from = Janet@Valade.com
112
Sending e-mail messages
PHP provides a function called mail that
sends e-mail from your script. The
format is as follows:
mail(address,subject,message,headers)
;
113
 address: The e-mail address that receives
the message
 subject: A string that goes on the subject line
of the e-mail message
 message: The content that goes in the e-mail
message
 headers: A string that sets values for e-mail
headers
114
 $to = “janet@valade.com”;
 $subj = “Test”;
 $mess = “This is a test of the mail function”;
 $headers =
bcc:techsupport@mycompany.com
 $mailsend = mail($to,$subj,$mess,$headers);
115
$to variable
You can send the message to more
than one person by using the following
statement:
$to=“janet@valade.com,me@mycompany.
com”;
116
$headers
Headers are optional. Only the first
three parameters are required.
The $mailsend variable contains TRUE
or FALSE. However, TRUE is no
guarantee that the mail will get to where
it’s going. It just means that it started
out okay.
117
Generating Personalized
PDF
Documents
 The PDF functions in PHP can create PDF files using
the PDFlib library which was initially created by
Thomas Merz and is now maintained by
» PDFlib GmbH.
 Be easy to design
 Work on many operating systems
 Be difficult to fraudulently duplicate or modify
118
Why use PDF with PHP?
Invoices for e-commerce sites
Report generation
 Anything that requires precise control
over printable output
119
pdf_new();
 First:create a blank pdf file
<anyname>.pdf
 To do this set a object, say $pdf, to handle
pdf manipulations.
$pdf = pdf_new();
To open the file, code we use the pdf_open_file
function.
 pdf_open_file($pdf, "C:abc.pdf");
120
 This should create a blank new pdf file
size 0kb
 The new file has no properties,
 We will need to use the pdf_set_info function
for this.
pdf_set_info($pdf, "Author", “prabhat");
pdf_set_info($pdf, "Title", "Creating a pdf");
pdf_set_info($pdf, "Creator", “prabhat");
121
pdf_begin_page
 PDF_begin_page ($pdfdoc , $width ,
$height )
pdf_begin_page($pdf, 595, 842);
122
123
pdf_findfont and pdf_setfont
Now it is time to assign a text
font for the information to be
displayed.
Arial font type with size of 14.
 $arial = pdf_findfont($pdf, "Arial", "host", 1);
pdf_setfont($pdf, $arial, 14);
124
pdf_show_xy
The x-values start from the left
hand side of the page and move
to the right.
The y-values start from the
bottom of the page and work
towards the top.
125
So if we wish to type some text
50 units from the left of the page
and 400 units from the bottom of
the page you would type the
following.
 pdf_show_xy($pdf, "<Type your info here>",50, 400);
126
pdf_end_page
pdf_end_page($pdf);
pdf_close($pdf);
127
Working with XML
128
Creating an XML Document
129
Working with Elements
Accessing a particular element now
becomes as simple as using parent-
>child notation to traverse the object
tree until that element is reached.
130
<?php
// load XML file
$xml = simplexml_load_file(‘books.xml') or die
("Unable to load XML!");
echo “title: " . $xml->book->title . "n";
echo "author: " . $xml->book->author. "n";
?>

More Related Content

What's hot (20)

PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
Intermediate PHP
Intermediate PHPIntermediate PHP
Intermediate PHP
 
Php variables (english)
Php variables (english)Php variables (english)
Php variables (english)
 
Basic PHP
Basic PHPBasic PHP
Basic PHP
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Introducation to php for beginners
Introducation to php for beginners Introducation to php for beginners
Introducation to php for beginners
 
Symfony 2.0 on PHP 5.3
Symfony 2.0 on PHP 5.3Symfony 2.0 on PHP 5.3
Symfony 2.0 on PHP 5.3
 
Cli the other sapi pbc11
Cli the other sapi pbc11Cli the other sapi pbc11
Cli the other sapi pbc11
 
Cli the other SAPI confoo11
Cli the other SAPI confoo11Cli the other SAPI confoo11
Cli the other SAPI confoo11
 
News of the Symfony2 World
News of the Symfony2 WorldNews of the Symfony2 World
News of the Symfony2 World
 
Php with my sql
Php with my sqlPhp with my sql
Php with my sql
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
CLI, the other SAPI phpnw11
CLI, the other SAPI phpnw11CLI, the other SAPI phpnw11
CLI, the other SAPI phpnw11
 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop Notes
 
Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010
 
Php mysql
Php mysqlPhp mysql
Php mysql
 

Viewers also liked

Application of dual output LiDAR scanning system for power transmission line ...
Application of dual output LiDAR scanning system for power transmission line ...Application of dual output LiDAR scanning system for power transmission line ...
Application of dual output LiDAR scanning system for power transmission line ...Pedro Llorens
 
WE1.L10 - GRACE Applications to Regional Hydrology and Water Resources
WE1.L10 - GRACE Applications to Regional Hydrology and Water ResourcesWE1.L10 - GRACE Applications to Regional Hydrology and Water Resources
WE1.L10 - GRACE Applications to Regional Hydrology and Water Resourcesgrssieee
 
Setting up a gmail account
Setting up a gmail accountSetting up a gmail account
Setting up a gmail accountkeelyswitzer
 
Appendex d
Appendex dAppendex d
Appendex dswavicky
 
Groundwater Research and Technology, Stefan Schuster
Groundwater Research and Technology, Stefan SchusterGroundwater Research and Technology, Stefan Schuster
Groundwater Research and Technology, Stefan SchusterTXGroundwaterSummit
 
Preparing LiDAR for Use in ArcGIS 10.1 with the Data Interoperability Extension
Preparing LiDAR for Use in ArcGIS 10.1 with the Data Interoperability ExtensionPreparing LiDAR for Use in ArcGIS 10.1 with the Data Interoperability Extension
Preparing LiDAR for Use in ArcGIS 10.1 with the Data Interoperability ExtensionSafe Software
 
Appendex b
Appendex bAppendex b
Appendex bswavicky
 
300 Years of Groundwater Management, Charles Porter
300 Years of Groundwater Management, Charles Porter300 Years of Groundwater Management, Charles Porter
300 Years of Groundwater Management, Charles PorterTXGroundwaterSummit
 
Ch7(publishing my sql data on the web)
Ch7(publishing my sql data on the web)Ch7(publishing my sql data on the web)
Ch7(publishing my sql data on the web)Chhom Karath
 
Final morris esri_nwgis_lidar
Final morris esri_nwgis_lidarFinal morris esri_nwgis_lidar
Final morris esri_nwgis_lidarEric Morris
 
Chapter 7 Multimedia
Chapter 7 MultimediaChapter 7 Multimedia
Chapter 7 MultimediaPatty Ramsey
 
CIS 110 Chapter 1 Intro to Computers
CIS 110 Chapter 1 Intro to ComputersCIS 110 Chapter 1 Intro to Computers
CIS 110 Chapter 1 Intro to ComputersPatty Ramsey
 
Appendex f
Appendex fAppendex f
Appendex fswavicky
 
5 Accessing Information Resources
5 Accessing Information Resources5 Accessing Information Resources
5 Accessing Information ResourcesPatty Ramsey
 
Ch2(working with forms)
Ch2(working with forms)Ch2(working with forms)
Ch2(working with forms)Chhom Karath
 
Chapter 9 Asynchronous Communication
Chapter 9 Asynchronous CommunicationChapter 9 Asynchronous Communication
Chapter 9 Asynchronous CommunicationPatty Ramsey
 

Viewers also liked (20)

Application of dual output LiDAR scanning system for power transmission line ...
Application of dual output LiDAR scanning system for power transmission line ...Application of dual output LiDAR scanning system for power transmission line ...
Application of dual output LiDAR scanning system for power transmission line ...
 
PHP - Introduction to PHP Date and Time Functions
PHP -  Introduction to  PHP Date and Time FunctionsPHP -  Introduction to  PHP Date and Time Functions
PHP - Introduction to PHP Date and Time Functions
 
WE1.L10 - GRACE Applications to Regional Hydrology and Water Resources
WE1.L10 - GRACE Applications to Regional Hydrology and Water ResourcesWE1.L10 - GRACE Applications to Regional Hydrology and Water Resources
WE1.L10 - GRACE Applications to Regional Hydrology and Water Resources
 
Setting up a gmail account
Setting up a gmail accountSetting up a gmail account
Setting up a gmail account
 
Appendex d
Appendex dAppendex d
Appendex d
 
Groundwater Research and Technology, Stefan Schuster
Groundwater Research and Technology, Stefan SchusterGroundwater Research and Technology, Stefan Schuster
Groundwater Research and Technology, Stefan Schuster
 
Unix Master
Unix MasterUnix Master
Unix Master
 
Preparing LiDAR for Use in ArcGIS 10.1 with the Data Interoperability Extension
Preparing LiDAR for Use in ArcGIS 10.1 with the Data Interoperability ExtensionPreparing LiDAR for Use in ArcGIS 10.1 with the Data Interoperability Extension
Preparing LiDAR for Use in ArcGIS 10.1 with the Data Interoperability Extension
 
Chapter 5 Input
Chapter 5 InputChapter 5 Input
Chapter 5 Input
 
Appendex b
Appendex bAppendex b
Appendex b
 
300 Years of Groundwater Management, Charles Porter
300 Years of Groundwater Management, Charles Porter300 Years of Groundwater Management, Charles Porter
300 Years of Groundwater Management, Charles Porter
 
Ch7(publishing my sql data on the web)
Ch7(publishing my sql data on the web)Ch7(publishing my sql data on the web)
Ch7(publishing my sql data on the web)
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
Final morris esri_nwgis_lidar
Final morris esri_nwgis_lidarFinal morris esri_nwgis_lidar
Final morris esri_nwgis_lidar
 
Chapter 7 Multimedia
Chapter 7 MultimediaChapter 7 Multimedia
Chapter 7 Multimedia
 
CIS 110 Chapter 1 Intro to Computers
CIS 110 Chapter 1 Intro to ComputersCIS 110 Chapter 1 Intro to Computers
CIS 110 Chapter 1 Intro to Computers
 
Appendex f
Appendex fAppendex f
Appendex f
 
5 Accessing Information Resources
5 Accessing Information Resources5 Accessing Information Resources
5 Accessing Information Resources
 
Ch2(working with forms)
Ch2(working with forms)Ch2(working with forms)
Ch2(working with forms)
 
Chapter 9 Asynchronous Communication
Chapter 9 Asynchronous CommunicationChapter 9 Asynchronous Communication
Chapter 9 Asynchronous Communication
 

Similar to PHP Introduction Guide - Learn PHP Basics

Php a dynamic web scripting language
Php   a dynamic web scripting languagePhp   a dynamic web scripting language
Php a dynamic web scripting languageElmer Concepcion Jr.
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQLArti Parab Academics
 
Php basic for vit university
Php basic for vit universityPhp basic for vit university
Php basic for vit universityMandakini Kumari
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requireTheCreativedev Blog
 
Quick beginner to Lower-Advanced guide/tutorial in PHP
Quick beginner to Lower-Advanced guide/tutorial in PHPQuick beginner to Lower-Advanced guide/tutorial in PHP
Quick beginner to Lower-Advanced guide/tutorial in PHPSanju Sony Kurian
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009cwarren
 
basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)Guni Sonow
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHPBradley Holt
 
07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboardsDenis Ristic
 

Similar to PHP Introduction Guide - Learn PHP Basics (20)

PHP and MySQL.ppt
PHP and MySQL.pptPHP and MySQL.ppt
PHP and MySQL.ppt
 
Php a dynamic web scripting language
Php   a dynamic web scripting languagePhp   a dynamic web scripting language
Php a dynamic web scripting language
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
 
Php basic for vit university
Php basic for vit universityPhp basic for vit university
Php basic for vit university
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
 
unit 1.pptx
unit 1.pptxunit 1.pptx
unit 1.pptx
 
Php hacku
Php hackuPhp hacku
Php hacku
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
Quick beginner to Lower-Advanced guide/tutorial in PHP
Quick beginner to Lower-Advanced guide/tutorial in PHPQuick beginner to Lower-Advanced guide/tutorial in PHP
Quick beginner to Lower-Advanced guide/tutorial in PHP
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
 
PHP for hacks
PHP for hacksPHP for hacks
PHP for hacks
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)
 
Php
PhpPhp
Php
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
PHP - Web Development
PHP - Web DevelopmentPHP - Web Development
PHP - Web Development
 
Phphacku iitd
Phphacku iitdPhphacku iitd
Phphacku iitd
 
07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 

More from prabhatjon

Registration open for CCDAC AUG 2015 batch
Registration open for CCDAC AUG 2015 batchRegistration open for CCDAC AUG 2015 batch
Registration open for CCDAC AUG 2015 batchprabhatjon
 
C-CAT Exam Laptop Configuration
C-CAT Exam Laptop ConfigurationC-CAT Exam Laptop Configuration
C-CAT Exam Laptop Configurationprabhatjon
 
CDAC CCAT examination important question
CDAC CCAT examination important questionCDAC CCAT examination important question
CDAC CCAT examination important questionprabhatjon
 
Operating system and C++ paper for CCEE
Operating system and C++ paper for CCEEOperating system and C++ paper for CCEE
Operating system and C++ paper for CCEEprabhatjon
 
Some other Importent Question (Mix)
Some other Importent Question (Mix)Some other Importent Question (Mix)
Some other Importent Question (Mix)prabhatjon
 
Some question for Section C (Embeded )
Some question for Section C (Embeded )Some question for Section C (Embeded )
Some question for Section C (Embeded )prabhatjon
 
CCAT Aug 2013 paper
CCAT Aug 2013 paperCCAT Aug 2013 paper
CCAT Aug 2013 paperprabhatjon
 
GUESS FUNDAMENTAL PAPER FOE CCAT Feb 2014
GUESS FUNDAMENTAL PAPER FOE CCAT Feb 2014GUESS FUNDAMENTAL PAPER FOE CCAT Feb 2014
GUESS FUNDAMENTAL PAPER FOE CCAT Feb 2014prabhatjon
 
Cplus plus abd datastructure
Cplus plus abd datastructureCplus plus abd datastructure
Cplus plus abd datastructureprabhatjon
 
Instructions to candidates For DASDM
Instructions to candidates For DASDMInstructions to candidates For DASDM
Instructions to candidates For DASDMprabhatjon
 
Critical Aptitude Question
Critical Aptitude QuestionCritical Aptitude Question
Critical Aptitude Questionprabhatjon
 
Delta final paper
Delta final paperDelta final paper
Delta final paperprabhatjon
 
Aloha paper for cdac ccpp
Aloha paper  for  cdac ccppAloha paper  for  cdac ccpp
Aloha paper for cdac ccppprabhatjon
 

More from prabhatjon (20)

Registration open for CCDAC AUG 2015 batch
Registration open for CCDAC AUG 2015 batchRegistration open for CCDAC AUG 2015 batch
Registration open for CCDAC AUG 2015 batch
 
C-CAT Exam Laptop Configuration
C-CAT Exam Laptop ConfigurationC-CAT Exam Laptop Configuration
C-CAT Exam Laptop Configuration
 
CDAC CCAT examination important question
CDAC CCAT examination important questionCDAC CCAT examination important question
CDAC CCAT examination important question
 
Operating system and C++ paper for CCEE
Operating system and C++ paper for CCEEOperating system and C++ paper for CCEE
Operating system and C++ paper for CCEE
 
Oops Paper
Oops PaperOops Paper
Oops Paper
 
Some other Importent Question (Mix)
Some other Importent Question (Mix)Some other Importent Question (Mix)
Some other Importent Question (Mix)
 
Some question for Section C (Embeded )
Some question for Section C (Embeded )Some question for Section C (Embeded )
Some question for Section C (Embeded )
 
Core java
Core javaCore java
Core java
 
Oops Paper
Oops PaperOops Paper
Oops Paper
 
Os paper
Os paperOs paper
Os paper
 
CCAT Aug 2013 paper
CCAT Aug 2013 paperCCAT Aug 2013 paper
CCAT Aug 2013 paper
 
GUESS FUNDAMENTAL PAPER FOE CCAT Feb 2014
GUESS FUNDAMENTAL PAPER FOE CCAT Feb 2014GUESS FUNDAMENTAL PAPER FOE CCAT Feb 2014
GUESS FUNDAMENTAL PAPER FOE CCAT Feb 2014
 
Cplus plus abd datastructure
Cplus plus abd datastructureCplus plus abd datastructure
Cplus plus abd datastructure
 
Instructions to candidates For DASDM
Instructions to candidates For DASDMInstructions to candidates For DASDM
Instructions to candidates For DASDM
 
Dsda
DsdaDsda
Dsda
 
Critical Aptitude Question
Critical Aptitude QuestionCritical Aptitude Question
Critical Aptitude Question
 
Cyber law ipc
Cyber law ipcCyber law ipc
Cyber law ipc
 
Ccpp pune
Ccpp puneCcpp pune
Ccpp pune
 
Delta final paper
Delta final paperDelta final paper
Delta final paper
 
Aloha paper for cdac ccpp
Aloha paper  for  cdac ccppAloha paper  for  cdac ccpp
Aloha paper for cdac ccpp
 

Recently uploaded

Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxabhijeetpadhi001
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 

Recently uploaded (20)

Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 

PHP Introduction Guide - Learn PHP Basics

  • 2. 2 What is PHP?  PHP stands for PHP: Hypertext Preprocessor  PHP is a server-side scripting language, like ASP  PHP scripts are executed on the server  PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)  PHP is an open source software  PHP is free to download and use  PHP is an interpreted language.
  • 3. 3 What is a PHP File? PHP files can contain text, HTML tags and scripts PHP files are returned to the browser as plain HTML  PHP files have a file extension of ".php", ".php3", or ".phtml"
  • 4. 4 Why PHP?  PHP runs on different platforms (Windows, Linux, Unix, etc.)  PHP is compatible with almost all servers used today (Apache, IIS, etc.)  PHP is FREE to download from the official PHP resource: www.php.net  PHP is easy to learn and runs efficiently on the server side  PHP is an open-source projec
  • 6. 6 PHP: Development environment must contain at least three components:  A base operating system (OS) and server environment (usually Linux)  A Web server (usually Apache on Linux or IIS on Windows) to intercept HTTP requests and either serve them directly or pass them on to the PHP interpreter for execution  A PHP interpreter to parse and execute PHP code, and return the results to the Web server There’s also often a fourth optional but very useful component:  A database engine (such as MySQL) that holds application data, accepts connections from the PHP layer, and modifies or retrieves data from the database
  • 7. 7 PHP Syntax A PHP scripting block always starts with <?php and ends with ? >. A PHP scripting block can be placed anywhere in the document. <?php // this line of code displays a famous quotation echo ‘Love Can Make Any One Poet!'; ?>
  • 8. 8 Comments in PHP Single-line comments must be preceded by the // characters multiline comments must be enclosed within a /* ... */ comment block
  • 9. 9 Mixing PHP with HTML <html> <body> <?php echo "Hello World"; ?> </body> </html>
  • 10. 10 PHP Variables A variable is simply a container that’s used to store both numeric and non- numeric information Every variable name must be preceded with a dollar ($) symbol and must begin with a letter or underscore character So, for example, $root, $_num, and $query2
  • 11. 11 Assigning Values to Variables Assigning a value to a variable in PHP is quite easy: use the equality (=) symbol, which also happens to be PHP’s assignment operator. <?php // assign value to variable $name = ‘Prabhat’; ?> <h2> Welcome to <?php echo $name; ?>'s Blog! </h2>
  • 12. 12 Destroying Variables <?php // assign value to variable $car = 'Porsche'; // print variable value // output: 'Before unset(), my car is a Porsche' echo "Before unset(), my car is a $car"; // destroy variable unset($car); // print variable value // this will generate an 'undefined variable' error // output: 'After unset(), my car is a ' echo "After unset(), my car is a $car"; ?>
  • 15. 15 Assignment Operators = operator is Assignment Operator
  • 18. 18 The if Statement if (condition) code to be executed if condition is true; <?php // if number is less than zero // print message $number = -88; if ($number < 0) { echo 'That number is negative'; } ?>
  • 19. 19 The If...Else Statement if (condition) code to be executed if condition is true; else code to be executed if condition is false;
  • 20. 20 <?php // change message depending on whether // number is less than zero or not $number = -88; if ($number < 0) { echo 'That number is negative'; } else { echo 'That number is either positive or zero'; } ?>
  • 21. 21 The if-elseif-else Statement<?php // handle multiple possibilities // define a different message for each day $today = 'Tuesday'; if ($today == 'Monday') { echo 'Monday's child is fair of face.'; } elseif ($today == 'Tuesday') { echo 'Tuesday's child is full of grace.'; } elseif ($today == 'Wednesday') { echo 'Wednesday's child is full of woe.'; } elseif ($today == 'Thursday') { echo 'Thursday's child has far to go.'; } elseif ($today == 'Friday') { echo 'Friday's child is loving and giving.'; } elseif ($today == 'Saturday') { echo 'Saturday's child works hard for a living.'; } else { echo 'No information available for that day'; } ?>
  • 22. 22 The switch-case Statement<?php // handle multiple possibilities // define a different message for each day $today = 'Tuesday'; switch ($today) { case 'Monday': echo 'Monday's child is fair of face.'; break; case 'Tuesday': echo 'Tuesday's child is full of grace.'; break; case 'Wednesday': echo 'Wednesday's child is full of woe.'; break; case 'Thursday': echo 'Thursday's child has far to go.'; break; case 'Friday': echo 'Friday's child is loving and giving.'; break; case 'Saturday': echo 'Saturday's child works hard for a living.'; break; default: echo 'No information available for that day'; break; } ?>
  • 24. 24 The while Statement Syntax while (condition) code to be executed; <?php // repeat continuously until counter becomes 10 // output: 'xxxxxxxxx' $counter = 1; while ($counter < 10) { echo 'x'; $counter++; } ?>
  • 25. 25 The do-while Loop Syntax do { code to be executed; } while (condition);
  • 26. 26 <?php // repeat continuously until counter becomes 10 // output: 'xxxxxxxxx' $counter = 1; do { echo 'x'; $counter++; } while ($counter < 10); ?>
  • 27. 27 The for Loop  Syntax for (init; cond; incr) { code to be executed; }  init: Is mostly used to set a counter, but can be any code to be executed once at the beginning of the loop statement.  cond: Is evaluated at beginning of each loop iteration. If the condition evaluates to TRUE, the loop continues and the code executes. If it evaluates to FALSE, the execution of the loop ends.  incr: Is mostly used to increment a counter, but can be any code to be executed at the end of each loop.
  • 28. 28 <?php // repeat continuously until counter becomes 10 // output: for ($x=1; $x<10; $x++) { echo "$x "; } ?>
  • 30. 30 Create a PHP Function  All functions start with the word "function()"  Name the function - It should be possible to understand what the function does by its name. The name can start with a letter or underscore (not a number)  Add a "{"  - The function code starts after the opening curly brace  Insert the function code  Add a "}"  - The function is finished by a closing curly brace
  • 31. 31 <?php function nme() { echo "Kya hal hae DAC !"; } nme(); ?>
  • 32. 32 PHP Arrays  An array can store one or more values in a single variable name.  There are three different kind of arrays: Numeric array - An array with a numeric ID key Associative array - An array where each ID key is associated with a value Multidimensional array - An array containing one or more arrays
  • 33. 33 Numeric Arrays A numeric array stores each element with a numeric ID key. $names = array("Prabhat",“Nitesh",“shudhanshu");
  • 34. 34 <? Php $names[0] = “Arvind"; $names[1] = “Nitesh"; $names[2] = “shudhanshu"; echo $names[1] . " and " . $names[2] . " are ". $names[0] . C-DAC Students "; ?>
  • 35. 35 Associative Arrays <?php // define array $fruits = array('apple', 'banana', 'pineapple', 'grape'); ?>
  • 36. 36 The keys of the array must be unique<?php // define array $fruits = array( 'a' => 'apple', 'b' => 'banana', 'p' => 'pineapple', 'g' => 'grape‘ Echo “$fruit[“a”] is gud friut” ); ?>
  • 37. 37 Multidimensional Arrays  onion, 0.50  apple, 2.50  orange, 2.00  chicken, 3.50  potato, 1.00  Fish,5.00
  • 38. 38 $foodPrices[‘onion’] = 0.50; $foodPrices[‘apple’] = 2.50; $foodPrices[‘orange’] = 2.00; $foodPrices[‘chicken’] = 3.50; $foodPrices[‘potato’] = 1.00; $foodPrices[‘fish’] = 5.00;
  • 39. 39  $foodPrices [‘vegetable’] [‘onion’] = 0.50;  $foodPrices [‘vegetable’] [‘potato’] = 1.00;  $foodPrices [‘fruit’] [‘apple’] = 2.50;  $foodPrices [‘fruit’] [‘orange’] = 2.00;  $foodPrices [‘meat’] [‘chicken’] = 3.50;  $foodPrices [‘meat’] [‘fish’] = 5.00;
  • 40. 40 $foodPrices key value vegetable onion Potato 0.50 1.00 fruit orange apple 2.00 2.50 meat chicken Fish 3.50 5.00
  • 42. 42 Using multidimensional arrays in statements  $fishPrice = $foodPrices[‘meat’][‘fish’];  echo “The price of fish is Rs .” $fishprice ;
  • 43. 43 Sorting an Array in PHP sort(), to sort an array in ascending order
  • 45. 45  The output of this PHP code is: Alfred Robert Deepak Teresa Joshua Chandni Sadiq Vladimir
  • 49. 49  Now the output is: Vladimir Teresa Sadiq Robert Joshua Deepak Chandni Alfred
  • 50. 50 PHP Cookies  Users may set their browsers to refuse cookies  If your application depends on cookies, it won’t run if cookies are turned off.  PHP has features that work better than cookies.  PHP 5, PHP sessions can store information that is available for the entire session  You can store data in a database.  Users can’t delete the data in your database unexpectedly.
  • 51. 51 Setting Cookies with PHP:  PHP provided setcookie() function to set a cookie.  Name - This sets the variable name of the cookie and is stored in an environment variable called $_COOKIE or $HTTP_COOKIE_VARS variables. This variable is used while accessing cookies.  Value -This sets the value of the named variable and is the content that you actually want to store.  Expiry - This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed. Setcookie (variable_name, value, expire);
  • 52. 52 setcookie(“state”,”UP”); echo “Your home state is “. $_COOKIE[“state”]; or echo “Your home state is “. . $HTTP_COOKIE_VARS [“state”]; Your home state is UP
  • 53. 53 Setting expiration dates  The expiretime value sets the time when the cookie expires.  time: This function returns the current time in a format the computer can understand.  You use the time function plus a number of seconds to set the expiration time of the cookie  setcookie(“state”,”UP”,time()+3600); //expires in one hour  setcookie(“Name”,$Name,time() +(3*86400))//expires 3 days
  • 54. 54 mktime: This function returns a date and time in a format that the computer can understand. You must provide the desired date and time in the following order: hour, minute, second, month, day, and year  setcookie(“state”,”CA”,mktime(3,0,0,4,1,2009)); //Expires at 3:00 AM on April 1, 2009  setcookie(“state”,”CA”,mktime(13,0,0,,,)); //expires at 1:00 PM today
  • 55. 55 isset() isset() function to check if a cookie is set or not.
  • 56. 56 <html> <head> <title>Accessing Cookies with PHP</title> </head> <body> <?php if( isset($_COOKIE["name"])) echo "Welcome " . $_COOKIE["name"] . "<br />"; else echo "Sorry... Not recognized" . "<br />"; ?> </body> </html>
  • 57. 57 PHP Sessions A session is the time that a user spends at your Web site A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.
  • 58. 58  To make session information available, PHP does the following: 1. PHP assigns a session ID number. 2. PHP stores the variables that you want saved for the session in a file on the server 3. PHP passes the session ID number to every page. 4. PHP gets the variables from the session file for each new session page  The variables are available in the $_SESSION array. 5. A session ends when the user loses the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration
  • 59. 59 Opening and closing sessions Open the session with the session_start function, as follows: session_start(); The function first checks for an existing session ID number. If it finds one, it sets up the session variables. If it doesn’t find one, it starts a new session by creating a new session ID number.
  • 60. 60 Storing a Session Variable To save a variable in a session so that it’s available on later Web pages, store the value in the $_SESSION array, as follows: $_SESSION[‘varname’] = “Prabhat”;
  • 61. 61 Destroying a Session  If you wish to delete some session data, you can use the unset() or the session_destroy() function  session_destroy() will reset your session and you will lose all your stored session data. This function does not need any argument  unset() function to unset a session variable. its need argument
  • 64. 64 Using a form to upload a file You can display a form that allows a user to upload a file by using an HTML form designed for that purpose. The general format of the form is as follows:
  • 65. 65  The enctype attribute is used in the form tag. You must set this attribute to multipart/form-data when uploading a file to ensure the file arrives correctly.  A hidden field is included that sends a value (in bytes) for MAX_FILE_SIZE. If the user tries to upload a file that is larger than this value, it won’t upload. When sending the value for MAX_FILE_SIZE in your form, you need to consider two size settings in php.ini  The input field that uploads the file is of type file.
  • 66. 66 Note: The value for MAX_FILE_SIZE must be sent before the file is uploaded if you want the file size limit to apply to the uploading file. If you don’t like the location of the temporary directory, you can change it by changing upload_tmp_dir in the php.ini file.
  • 67. 67 Accessing information about an uploaded file  Along with the file, information about the file is sent with the form. This information is stored in the PHP built-in array called $_FILES.  $_FILES["fieldname"]["name"] - the name of the uploaded file  $_FILES["fieldname"]["type"] - the type of the uploaded file  $_FILES["fieldname"]["size"] - the size in bytes of the uploaded file  $_FILES["fieldname"]["tmp_name"] - the name of the temporary copy of the file stored on the server  $_FILES["fieldname"]["error"] - the error code resulting from the file upload
  • 68. 68 For Example  suppose you use the following field to upload a file: <input type=”file” name=”user_file”>  If the user uploads a file named test.txt by using the form $_FILES[user_file][name] = test.txt $_FILES[user_file][type] = text/plain $_FILES[user_file][tmp_name] = D:WINNTphp92C.tmp $_FILES[user_file][size] = 435
  • 69. 69 Moving uploaded files to their destination The general format of the statement that moves the file is as follows: move_uploaded_file(path/tempfilename,pat h/permfilename); tempfilename: element in $_FILES stores the temporary filename and location move_uploaded_file($_FILES[‘user_file’ ][‘tmp_name’],‘c:datanew_file.txt’);
  • 70. 70 Storing Data with PHP  Many applications require the long-term storage of information.  The information needs to be stored on the server  Information can be stored on the server in flat files or in databases.  Flat files are text files stored in the computer file system.  Database for data storage requires you to install and learn to use database software, such as MySQL or Oracle.
  • 71. 71 Using Flat Files Using a flat file requires three steps: 1. Open the file. 2. Write data into the file or retrieve data from the file. 3. Close the file.
  • 72. 72 Accessing files $fh = fopen(“filename”,”mode”) The variable, $fh, referred to as a file handle
  • 73. 73 The filename can be a simple filename (filename.txt), a path to the file (c:/data/filename.txt), or a URL (http://yoursite.com/filename.txt)
  • 74. 74 Opening files in read mode $fh = fopen(“file1.txt”,”r”); If the file can’t be found, a warning message Warning: fopen(file1.txt): failed to open stream: No such file or directory in d:test2.php on line 12 Remember, a warning condition does not stop the script. The script continues to run, but the file doesn’t open, so any later statements that read orwrite to the file aren’t executed.
  • 75. 75 a die statement $fh = fopen(“file1.txt”,”r”) or die(“Can’t open file”);
  • 76. 76 Opening files in write mode $fh = fopen(“c:/testdir/file1.txt”,”w”); You can check whether a directory exists before you try to write a file into it by using the following statements: If(is_dir(“c:/tester”)) { $fh = fopen(“c:/testdir/file1.txt”,”w”); }
  • 77. 77 Closing a file To close a file after you have finished reading or writing it, use the following statement: fclose($fh);
  • 78. 78 Writing to a file  After you open the file, you can write into it by using the fwrite statement, which has the following general format: fwrite($fh,datatosave);
  • 79. 79 For example, $today = date(“Y-m-d”); $fh = fopen(“file2.txt”,”a”); fwrite($fh,$today); fclose($fh); Note:-for data in separate line use fwrite($fh,$today”n”);
  • 80. 80 Reading from a file You can read from a file by using the fgets statement, which has the following general format: $line = fgets($fh) $fh holds the pointer to the open file PHP recognizes the end of the file, and provides a function feof to tell you when you reach the end of the file.
  • 82. 82 Working with Databases  There are a large number of database management systems currently available, some commercial and some free  IBM DB2  Informix  Ingres  Microsoft SQL Server (MS SQL)  mSQL  MySQL  Oracle  PostgreSQL  Sybase
  • 83. 83 Choosing a RDBMS Choosing a RDBMS depends on your needs. Cost Features Resources Some RDBMSs require more resources, such as disk space and memory, than others. Like oracle
  • 85. 85 Understanding SQL Statements Data Definition Language (DDL) DDL consists of statements that define the structure and relationships of a database and its tables. Typically, these statements are used to create, delete, and modify databases and tables; specify field names and types; and set indexes.
  • 86. 86  ● Data Manipulation Language (DML) DML statements are related to altering and extracting data from a database. These statements are used to add records to, and delete records from, a database; perform queries; retrieve table records matching one or more user-specified criteria; and join tables together using their common fields.
  • 87. 87 ● Data Control Language (DCL) DCL statements are used to define access levels and security privileges for a database. You would use these statements to grant or deny user privileges; assign roles; change passwords; view permissions; and create rule sets to protect access to data.
  • 88. 88
  • 89. 89 Creating and Populating a Database Creating the Database mysql> CREATE DATABASE music; Query OK, 1 row affected (0.05 sec) Next, select this newly database as the default for all future commands with the USE statement: mysql> USE music; Database changed
  • 90. 90 Adding Tables mysql> CREATE TABLE artists ( -> artist_id INT(4) NOT NULL PRIMARY KEY AUTO_INCREMENT, -> artist_name VARCHAR (50) NOT NULL, -> artist_country CHAR (2) NOT NULL -> ); Query OK, 0 rows affected (0.07 sec)
  • 91. 91  The NOT NULL modifier ensures that the field cannot accept a NULL value after each field definition  The PRIMARY KEY modifier marks the corresponding field as the table’s primary key.  The AUTO_INCREMENT modifier, which is only available for numeric fields, tells MySQL to automatically generate a value for this field every time a new record is inserted into the table, by incrementing the previous value by 1.
  • 93. 93 Adding Records mysql> INSERT INTO artists (artist_id, artist_name, artist_country) -> VALUES ('1', 'Aerosmith', 'US'); Query OK, 1 row affected (0.00 sec)
  • 94. 94 Executing Queries  SQL allows you to search for records matching specific criteria using the SELECT statement mysql> SELECT artist_id, artist_name FROM artists; artist_id artist_name 1 Kishore 2 Rafi 3 Lata 3 rows in set (0.00 sec)
  • 95. 95 Using PHP with a database Whichever database you’re using, the steps to interact with a database are similar: 1. Connect to the database. 2. Send an SQL query that contains instructions for the database software. 3. If you retrieved data from the database, process the data. 4. Close the connection to the database.
  • 96. 96 Connecting to the database  Location:  The database does not need to be on the same computer where PHP is installed. Therefore, you need to tell the PHP connect function the name of the computer where the database is located (the hostname). You can supply either a domain name (such as mycompany.com) or an IP address (such as 172.17.204.2). If the database is on the same computer as PHP, you can use localhost for the hostname.  Account name  You must provide a valid account name that can be used to access the database. The database administrator sets this up. If you’re using a Web hosting company, you will be given a valid account name.
  • 97. 97 Password: You have to have a valid password to access the database. The database administrator sets this up. If you’re using a Web hosting company, you will be given a valid password for your account. Database name: An RDBMS can create and maintain many databases, so you need to tell it which database you want to use.
  • 98. 98 $host = “localhost”; $account = “admin”; $password = “secret”; $dbname = “music”;
  • 99. 99 The basic command  mysql_connect($hos, $account, $password);  The password is optional, depending on whether this particular database user requires one (it’s a good idea). If not, just leave that variable off.
  • 100. 100 mysqli function mysqli_connect, which adds a fourth parameter allowing you to select a database in the same function you use to connect.  mysqli_connect($hos, $account, $password, $dbname );
  • 101. 101 mysql_select_db If you need it only if you want to use multiple databases on the same connection. Next, you’ll want to choose a database to work on: mysql_select_db($database); if you’re using variables; or mysql_select_db(‘phpbook’); if you’re using a literal string.
  • 102. 102 mysql_query() A database query from PHP is basically a MySQL command wrapped up in a tiny PHP function called mysql_query(). This is where you use the basic SQL workhorses of SELECT, INSERT, UPDATE, and DELETE
  • 103. 103 mysql_query(“SELECT * FROM Product WHERE ID<10”); Or $query = “SELECT * FROM Product WHERE ID<10”; $result = mysql_query($query);
  • 104. 104 Fetching Data Sets  mysql_fetch_row: Returns row as an enumerated array  mysql_fetch_object: Returns row as an object  mysql_fetch_array:  Returns row as an associative array  mysql_result: Returns one cell of data
  • 105. 105 mysql_fetch_row $query = “SELECT ID, LastName, FirstName FROM users WHERE Status = 1”; $result = mysql_query($query); while ($name_row = mysql_fetch_row($result)) { print(“$name_row[0] $name_row[1] $name_row[2]<BR>n”); } This code will output the specified rows from the database, each line containing one row or the information associated with a unique ID (if any).
  • 106. 106 mysql_fetch_object  Function do the same task, except the row is returned as an object rather than an array. $query = “SELECT ID, LastName, FirstName FROM users WHERE Status = 1”; $result = mysql_query($query); while ($row = mysql_fetch_object($result)) { echo “$row->ID, $row->LastName, $row- >FirstName<BR>n”; }
  • 107. 107 mysql_fetch_array  This function offers the choice of results as an associative or an enumerated array or both $query = “SELECT ID, LastName, FirstName FROM users WHERE Status = 1”; $result = mysql_query($query); while ($row = mysql_fetch_array($result)) { echo “$row[‘ID’], $row[‘LastName’], $row[‘FirstName’]<BR>n”; }
  • 108. 108 Remember that mysql_fetch_array can also be used exactly the same way as mysql_fetch_row—with numerical identifiers rather than field names.
  • 109. 109 Setting up PHP to send e-mail  E-mail is sent by an outgoing e-mail server. To send e-mail, you need access to an outgoing server. If you can send e-mail from your own computer right now, you’re using an outgoing server.  Your outgoing mail server is typically an SMTP (Simple Mail Transfer Protocol) server. Whether you use a LAN at work, a cable modem at home, or an ISP via a modem, you send your mail with an SMTP server, and the server has an address that you need to know.
  • 110. 110 With the name of your outgoing mail server in front of you, open php.ini [mail function] ; For Win32 only. SMTP = localhost ; For Win32 only. ;sendmail_from = me@localhost.com
  • 111. 111  Windows users need to change the first two settings. The first setting is where you put the name of your outgoing server, as follows: SMTP = mail.ispname.com  The second setting is the return address that is sent with all your e-mail. Change the setting to the e-mail address you want to use for your return address, as follows: sendmail_from = Janet@Valade.com
  • 112. 112 Sending e-mail messages PHP provides a function called mail that sends e-mail from your script. The format is as follows: mail(address,subject,message,headers) ;
  • 113. 113  address: The e-mail address that receives the message  subject: A string that goes on the subject line of the e-mail message  message: The content that goes in the e-mail message  headers: A string that sets values for e-mail headers
  • 114. 114  $to = “janet@valade.com”;  $subj = “Test”;  $mess = “This is a test of the mail function”;  $headers = bcc:techsupport@mycompany.com  $mailsend = mail($to,$subj,$mess,$headers);
  • 115. 115 $to variable You can send the message to more than one person by using the following statement: $to=“janet@valade.com,me@mycompany. com”;
  • 116. 116 $headers Headers are optional. Only the first three parameters are required. The $mailsend variable contains TRUE or FALSE. However, TRUE is no guarantee that the mail will get to where it’s going. It just means that it started out okay.
  • 117. 117 Generating Personalized PDF Documents  The PDF functions in PHP can create PDF files using the PDFlib library which was initially created by Thomas Merz and is now maintained by » PDFlib GmbH.  Be easy to design  Work on many operating systems  Be difficult to fraudulently duplicate or modify
  • 118. 118 Why use PDF with PHP? Invoices for e-commerce sites Report generation  Anything that requires precise control over printable output
  • 119. 119 pdf_new();  First:create a blank pdf file <anyname>.pdf  To do this set a object, say $pdf, to handle pdf manipulations. $pdf = pdf_new(); To open the file, code we use the pdf_open_file function.  pdf_open_file($pdf, "C:abc.pdf");
  • 120. 120  This should create a blank new pdf file size 0kb  The new file has no properties,  We will need to use the pdf_set_info function for this. pdf_set_info($pdf, "Author", “prabhat"); pdf_set_info($pdf, "Title", "Creating a pdf"); pdf_set_info($pdf, "Creator", “prabhat");
  • 121. 121 pdf_begin_page  PDF_begin_page ($pdfdoc , $width , $height ) pdf_begin_page($pdf, 595, 842);
  • 122. 122
  • 123. 123 pdf_findfont and pdf_setfont Now it is time to assign a text font for the information to be displayed. Arial font type with size of 14.  $arial = pdf_findfont($pdf, "Arial", "host", 1); pdf_setfont($pdf, $arial, 14);
  • 124. 124 pdf_show_xy The x-values start from the left hand side of the page and move to the right. The y-values start from the bottom of the page and work towards the top.
  • 125. 125 So if we wish to type some text 50 units from the left of the page and 400 units from the bottom of the page you would type the following.  pdf_show_xy($pdf, "<Type your info here>",50, 400);
  • 128. 128 Creating an XML Document
  • 129. 129 Working with Elements Accessing a particular element now becomes as simple as using parent- >child notation to traverse the object tree until that element is reached.
  • 130. 130 <?php // load XML file $xml = simplexml_load_file(‘books.xml') or die ("Unable to load XML!"); echo “title: " . $xml->book->title . "n"; echo "author: " . $xml->book->author. "n"; ?>