The MySQL distribution consist of three numbers and a suffix; for example, mysql-5.0.14-rc.
• The first number (5) is the major version and describes the file format. All MySQL 5
releases have the same file format.
• The second number (0) is the release level. the major version and release level combines
the release series number.
• The third number (14) is the version number or minor number within the release series.
This is incremented for each new release.
For each minor update, the last number is increased. When there are major new features with
previous versions, the second number is incremented. When the file format changes, the first
number is increased.
How to get mysql s/w: MYSQL AB company develops and maintains the mysql database server
on website is http://www.mysql.com/downloads or http://dev.mysql.com .in this websites there are
containing number of o/s platform distributions. Select the one distribution file in specific os. You
will install the mysql on linux then you will choose to rpm extension or .tar.gz extension or you
will install on windows choose win32 binary distribution.
Process of Installing mysql on linux you use two ways i.e RPM or Binaries
• RPM installation – it is fast and simple installation The only drawback here is that
MySQL is not installed into a single destination it's install the several directories.
• Installing binaries – downloading installation files from the mysql.com website, copying
them into a directory of your choice, and doing some simple configuration.
To perform a minimal installation from RPMs, you can type the following at your Linux prompt
i.e
Another installation method is to install MySQL from binary. This method requires gunzip and tar
files (files with .tar.gz extension) and also requires to create groups and users on the system.
1. If your system does not contain a user and group for mysql then u will create user and
groups as follows
The above will create a user that has login permissions to your server.These commands add
the mysql group and the mysql user.
2. Pick the directory under which you want to intsallation files and change location into it
shell> cd /usr/local
3. Unpack the distribution, which creates the installation directory. Then create a symbolic link to
that directory:
shell> cd mysql
You will find several files and subdirectories in the mysql directory i.e for installation purposes
are the bin and scripts subdirectories:
The first command changes the owner attribute of the files to the mysql user. The second
changes the group attribute to the mysql group.
If you have not installed MySQL before, you must create the MySQL data directory and
initialize the grant tables:
this command runs as root, so change ownerships to root because data directory and it
contents with mysql as the owner.
After creating or updating the grant tables, you need to restart the server manually.
7. Most of the MySQL installation can be owned by root .this, run the following commands as
root in the installation directory:
8. After everything has been unpacked and installed, To start the MySQL server, use the
following command:
Now, before you do anything else, set root user's password (!)
1. If you installed mysql software on windows then you can download the MySQL
Server(win32 installer) software from the MySQL website. after download it stores the file
on your Windows Desktop.
2. now double click the setup.exe file. It will be display the mysql setup wizard as shown in
below figure. In this window select the next tab.
3. after clcik next it will display the setup type window. It provides 3 setup type options i.e
typical, custom, complete. Now here Choose the custom type option and click the next
shown in below fig.
4. next it display’s custom setup window. Here change the all features are installed and
change the installation directory i.e “c:\server\mysql\” and click the next tab.(shown in
below fig)
5. after clcik the next tab the wizard ready to began installation when ever click the install tab.
(as shown in below fig)
6. click the install tab now it installs the files of mysql server in proper location.
7. When the installation is complete it display the wizard complete window. In this window
select the configure option and click the finish tab.
8. when ever click the finish tab it displays the configuration window welcome screen, click
the next.(as shown in below fig)
9. now go to the next wizard. you will see two options for server configuration i.e detailed
configuration, standard configuration options. You can select the detailed configuration
option and click the next as shown in below fig
10. display the next wizard, in this wizard set the windows options i.e select the intsall as
windows service and give the service name i.e mysql in service name textbox and select the
include bin directory in windows path option , click the next.(as shown in below fig.)
11. next wizard is displayed. Here set the security settings i.e type the new root password and
type the confirm password, click next as shown in below fig.
12. now ready to execute all settings to the configuration when ever u click the execute button.
select the execute button, now create the configuration file and start the mysql service.
Click finish tab to close the wizard.
You are connecting mysql from host by using username and password. Username and
password is correct then we will moves to second step otherwise your host can not
connect to server.
If Username and password correct then Mysql verifies to sql command privileges that
you are accessing table ,field or database.
if step 1 fails then it displays the error but you want be able to continue the step2. for example,
suppose that you are connecting to mysql with username of jyothi and password ab123. it displays
the error message if connection variables is incorrect for any following reasons:
Password is incorrect
Username jyothi does not exist.
User jyothi can connect from localhost but cannot use the mydb database.
Example of error like following:
Shell>mysql –h localhost –u jyothi –pab123 test
Error 1045: Access denied for user:”jyothi@localhost” (password: YES)
If user jyothi with password ac123 is allowed to connect the database, mysql checks the actions
that jyothi can perform step2. here mysql allows the jyothi to select the data but it not allowed to
insert data.
Examples:
Shell> mysql –h localhost –u jyothi –pab123 test
Reading tables information only
Welcome to the mysl monitor.
Your mysql connection Id is 12 to server version:5.0.20…………
Mysql>select * from jyo_table;
ID Name
1 Nalini
2 kumari
Suppose only perform select the privileges on all table in all database like this query.
Grant select
On *.*
To ravi@”%”
Identified by “abc123”;
Note: * means access all tables on all databases and % means access all localhosts.
It perform all the privileges on all table in all database connecting using any local host like this ,
Grant All
On *.*
To ravi@”%”
Identified by “abc123”;
Removing privileges instead of the grant command, you can use revoke command.
Syntax:
Revoke privileges
On databasename.tablename
Fom username@hostname
for example the user ravi contains privileges is insert and select in all tables on employee
database , you can removing the insert privileges by using revoke command
Revoke insert
On employee.*
Fom ravi@”%”;
10
1. download the apache server from apache website in internet. this software is a free
software not purchased because apache is open source.
2. the apache website is httpd.apache.org. in this website select the one windows
distribution file.
3. after download the apache s/w just go to file location in your local system.
4. double click the apache download file to start the installation process.
5. it displays the windows installer welcome screen as shown in below fig.
6. click next to continue the installation process and next you will accept apache
license agreement, click next.
7. after accept the license , the installer presents you with brief introduction to apache.
That is it provides basic information about your computer, as shown in below
figure.
8. it includes network domain(network address) for the server and name of the server,
administrator email address. Select the option is for all users, on port as a service.
this option refers to apache server starts manually when windows will start. Click
next.
11
9. the next screen enables to choose the type of installation: it displays two options i.e
typical and custom.
10. you can select custom option click next. Here change the apache installation
directory i.e c:\server\Apache2 and click next.
12. successfully installed apache server ,it displays the installation wizard completed
screen, here click the finish.
13. now the apache server runs on your system manually. Check The apache server
runs successful or not, just doing following i.e open the browser gives the
http://localhost request. it displays the its work, that means server working
successfully.
Installing Apache on linux/unix:
Successfully install the Apache on linux it follows genrel steps i.e
Download the software
Run the configuration
Install the software
Download the software:
The downloading the apache source code from http://httpd.apche.org/download.cgi website. In
this website there are number of distribution files with tar and gzip(compressed file). Now
download the one of the file is httpd-2.2.verion.tar.gz in apache website, here version is most
release of Apache. For example , Apache version 2.2.8 is distributed as a file named http://httpd –
2.2.8.tar.gz. store the download file in a directory for source files such as /usr/local/src/.
Uncompressing code and Run the configuration:
You can uncompress the software by using following command.
Shell>gun zip < httpd-2.2.8.tar.gz | tar xvf –
Shell> ./configure
To configure Apache to install itself in aspecific location to /usr/local/apache/ and enable the use
od mod_so, the following command is
Shell> ./configure—prefix=/usr/local/apach--enable-so
………..
Configure ok
Installing apache:
after configure or compilation is finished, you can install the Apache by using make command at
the linux prompt. i.e type the following command is installed the apache
shell>make install
………………..
12
• Install_logfile
• Access_logfile
• Error_logfile
The install log file contains the apache server installation information. The access_log file is for
tracking client requests. The error_log file is for recording important events, such as errors.
Install_log file:
This file includes entire server information at the time of installation i.e server name, server root,
server port, domain name etc.
Access_log file:
This file stores server accessed information. when a client requests a file from server. Apache
records information with request, IP address, HTTP status code and time of access. Shows sample
log file entries like as below
The first line indicates access the server at first time and second line indicates accessed the php
file.
Error_log file:
The error_log file includes error messages, startup messages. Suppose the client gives the request
to server i.e execute h1.php. but server does not contain this file it provides the error information
from error log file. Shows as below error_log entries.
[Wed Aug 25 21:21:02 2010] [notice] Child 332: Starting thread to listen on port 80.
[Wed Aug 25 23:46:11 2010] [error] [client 127.0.0.1] script 'C:/server/apache2/htdocs/hi.php'
not found or unable to start
The apache server executes and stops also by using commands. The apache server has contain
some apache related commands i.e
13
[Note: the apache commands are executes the httpd executable file. The httpd file is contains
c:\server\apache\bin\. So execute all commands in c:\server\apache\bin.]
-k install : this command is used to install the apache service.
Syntax: httpd -k install
Example: c:\server\apache2\bin>httpd -k install
Apache service is started
14
1) if u want to installing the php on your windows system , now you have to go to the php
website and download the php distribution files. i.e the website link is
http://www.php.net/downloads.
2) After download the php zip file, now go to download folder in your system to find the file
is called php-5.2.3-Win32.zip.
3) Extract the content of this file to C:\server\php. Now all of the files from the php-5.2.3-
Win32 folder and place them directly in C:\server\php.
4) After extract the files, set the php path to operating system variable. Now we need to add
C:\server\php to Environment Variables
Path setting procedure:
I. right click on My Computer icon on your desktop and choose Properties. Then
choose Advanced tab and click Environment Variables button (like as below fig).
II. Now select Path from the System variables list in the bottom part of the window and
click Edit tab (below fig)
15
III. In the new window click inside the Variable value: box and press End button on
your keyboard. Now type the c:/server/php after put the semicolon.
IV. Click the ok buttons until close the system properties windows. And restart the
computer
5) Next step will be to find out PHP is working or not, here just Go to Start -> Run and type
cmd. Now Display the command prompt, In this command prompt window type php -v. if
success fuly installed it displays the php version number otherwise none.
6) Next step change the configuration settings of php. Now open php configuration file. i.e
go to c:\server\php here find out the php.ini recommended file.
7) Rename that file to php.ini. Open this file and make the following changes like as below:
I. identify line with doc_root = and change it to:
doc_root = C:\webserver\Apache2\htdocs
II. identify line with extension_dir = "./" and change it to:
extension_dir = C:\webserver\php\ext
8) save and close the file.
9) Next step change the Apache configuration settings. Now open the Apache configuration
file i.e go to c:\server\Apache2\conf here open the httpd.conf file and changes like as below
sections.
I. identify LoadModule section and here add the following line is
LoadModule php5_module "C:\server\php\php5apache2_2.dll"
II. identify AddType section and add the following line is
AddType application\x-httpd-php .php
III. lastly place the following line i.e
PHPIniDir "C:\server\php\"
10) save and close the apache configuration file. Now restart the apache server.
Testing your installation:
To test php installation is to create a small test script by using phpinfo() function. This
function will display the list of configuration information. Open text editor type the following
line i.e
<?Php
phpinfo();
?>
16
Save the file as phpinfo.php into c:\server\apache2\htdocs. next start the server and open the
browser and type the following URL:
http://localhost/phpinfo.php.
[->You should see now a PHP information page (like as below fig)]
17
UNIT-II
PHP BASICS
18
Introduction of PHP:
PHP stands for personal home page it is implemented RASMUS LERDORF , 1995 using C
and Perl languages. It is used to develop the dynamic web applications.
The first version of php is php 1.0/F.I (F.I means form interpreter)
It is server side scripting language and it has alias name is hypertext preprocessor.
Php 1.0 to upto php 4.0 not contains O.O.P features. And php 5.0 version completely
implement O.O.P features.
Java is not user friendly but php is user friendly.
Features of PHP:
19
Versions of PHP:
Php 1.0:
• this is the basic version of php developed by rasmus lerdorf in 1995
• it is used to find out the hit count how many getting to the web server.
• It is not a server side scripting language.
• It is used to handle the server side request.
Php 2.0:
• Php 2.0 is released in 1997. it is introduced as server side scripting language .
• Collection of logins , password access
• It supports different database servers.
• It supports file uploads and many functions.
Php 3.0:
• the php 3.0 version is developed by Andi Gujmanj, suraski in 1998.
• It is completely server side scripting language.
• The Alias name of php is hyper text preprocessor provided from these version.
• It supports multiplatform.
• It is cross platform.
• It supports email functions.
Php 4.0:
• This version relased by zend engine in 2000.
• It is cross platform and cross server.
• This version include some advanced features like http sessions, supports flash,
XML, pdf etc.
• it contains smarty templating system. Which is used to develop web applications
very fast.
Php 5.0:
• Php 5.0 relasd in 20005, zend engine
• Php 5.0 contains complete object oriented programming structure. It supports
inheritance, abstraction, access specifiers, encapsulation etc.
• It supports the exception handling concepts.
• Supports web services and XML support.
[Note: some important points of php script: every php script extension should be “.php” or
“.phtml”. every php statement ends with semicolon.]
…….
…….
?>
<?php
echo “hello php script……”;
?>
Save the script i.e hello.php from c:/server/apache2/htdocs/. Next start the server and open the
browser give the request to server i.e http://localhost/hello.php shown below fig.
Beginning and ending a block of php statements: (or) types of php style tags:
The php engine identify the php block with php style tags. Php contains special style tags that is
used to implement the php script. Every php script contains beginning and ending blocks. there are
four types of style tags. i.e
1) Standard tags:
The standard start tag is <?php and end tag is ?>. the implementing of php script by using
standard tags is shown in below
<?php
echo “hello standard tags”;
?>
2) Short tags:
The short start tag is <? And end tag is ?>. implementing of php code by using short tags
also shown in below code
<?
echo “hello short tags”;
?>
Note: the short tags are directly not executed. We can go to php.ini configuration here find
short tags and change the short_open_tag is set to on.
i.e short_open_tag=on;
3) Asp tags:
21
The Asp start tag is <% And end tag is %>. implementing of php code by using Asp tags
also shown in below code
<%
echo “hello Asp tags”;
%>
Note: the Asp tags are directly not executed. We can go to php.ini configuration here find
Asp tags and change the Asp_tags is set to on.
i.e asp_tags=on;
4) Script tags:
The script start tag is <script language=”php”> And end tag is </script>. implementing
of php code by using script tags also shown in below code
<script language=”php”>
echo “hello short tags”;
</script>
The Echo statement and print() function: (or) (output functions in php):
Print(): print() is a function. This function display the data on webpage and returns a true or false
values. By using print function we can print only one statement.
Example:
<?php
Print(“hello php”);
?>
Output: hello php
Echo statement: echo is a statement . this statement is used to print the multiple statements at
once. It does not return any values. The echo statement performance is faster than print().
Example:
<?php
Echo “welcome”.”bsc III year”.”students”;
?>
Combining HTML and PHP:
The simply adding the HTML tags outside of PHP start and end tags, as shown in below example.
(or) the html tags are must be enclosed with double quotes in php statements.
Example:
<html>
<head>
<title>welcome</title>
</head>
<body><b><font size=14>
<?php
Echo “welcome php script……”;
?>
</b>
22
</body>
</html>
Save: c:\server\apache2\htdocs\welcome.php
Start the server and Open browser give the request i.e http://loclhost/welcome.php
Output:
23
Php is loosly –typed language because the programmers did not provide the data types at the time
of variable declaration.
<?php
$txt="Hello World!";
$x=16;
Echo $txt;
Echo $x;
?>
Local variables
Global variables
Static variables
Super global varables.
Local variables: A variable declaration with in the function that variable scope is only
with in the function.
Ex:
<?php
Function f1()
{
$a=100;
Echo $a;
}
f1();
echo $a; //error because a is local variable.
?>
Global variable: A variable declaration in global. The scope of variable is entire the script.
Php we can’t access global variables directly from a function by using global keyword we
can access the global variables.
Ex:
<?php
$a=120;
function f1()
{
Global $a;
Echo $a;// it prints 120
}
?>
Static variables: static is keyword. A vaiable is preceded by static keyword that variable is
called static variable. Assign the values into the Static variables only one time.
Ex:
<?php
Function f1()
{
Static $a=10;
Echo $a;
$a++;
}
F1();// it prints 10
F1();// it prints 11
F1();// it prints 12
Super Global variables: php is providing no of super global variables to access the
values from different locations.
• $_GET: this variables is used to access the get method posted values.
25
• $_POST: this variable is used o access the post method posted values.
• $_REQUEST: this variable is used to access the get, post method posted values.
• $_COOKIE: this variable is used to get the values from cookie.
• $_SESSION: It is used to read the values of session variables.
• $_FILES: this is used to access the uploaded file information.
26
1) Array: An array is collection of elements. In php we can store different data type
values in an array variable.
Ex: $arr=array(10,20,34.5);
Echo $arr[1];// it prints 20.
Is_array(variable): it returns 1 when the variable stores the array values.
Ex: echo is_array($arr);// it returns 1
2) Null data type: In php null is not a value. Based on 2 conditions we can declare a
variable as null data type.
i) a variable is not assign with a value. Ex: $a; // it contains null value
ii) a variable is assign with null. Ex: $a=null;
is_null(): it returns one when the variable holds null value.
Ex: $a=null;
Echo is_null($a); // it prints 1
Write a php script Example of testing the type of variable
<?php
$a;
echo "is null value?".is_null($a)."<br />";
$a=123;
echo "is integer value?".is_int($a)."<br />";
$a=12.56;
echo "is float value?".is_float($a)."<br />";
$a="ganesh";
echo "is string ?".is_string($a)."<br />";
$a=true;
echo "is boolean ?".is_bool($a)."<br />";
$a=10;
echo "is array ?".is_array($a);
?>
27
-> Save the file in c:/server/apache2/htdocs/data.php. And open the browser gives the request to
server. i.e http://localhost/data.php.
o/p: is null value?1
is integer value?1
is float value?1
is string ?1
is boolean ?1
is array ?
<?php
$a=25;
Echo “is integer?”.is_int($a);
Settype($a,’float’);
Echo “is float?”.is_float($a);
$ab=”abc”;
Settype($ab,’integer’);
Echo “is string?”.$ab;
?>
o/p: is integer?1
is float? 1
is string?
28
Assignment Operators: assignment operator is used to assign the values to variables and
expressions are assign to variables.
Comparison Operators:
comparision operator performs compare and test the given operands. It returns true or false values.
Logical Operators:
29
Concatenation operator:
concatenation operator is represented by single period (.)it used to combines more than one string
or statements.
Nam e example
Operator
. Concatenation $a=”hello”;
$b=”php”;
Echo $a.$b;//it displays hello php
Constants:
Constants refers to fixed values it doesn’t change the value at the time of execution of script.
A variable can be defined constant, it doesn’t change the variable value in entire script. In php, A
variable defines a constant by using define () built-in function.
To use the define function , it place the name of the constant and gives the value within the
parentheses and separated by comma
Syntax:
define(“constant name”,value);
Ex:
Write a php script Example of defining and accessing a constant
<?php
define(“year”,2010);
echo “the current year is”.year;//it prints 2010
?>
Types of Errors in PHP:
30
Control functions are used to control the flow of execution. The control functions are two types in
Php. i.e switching flow and loops.
Switching flow (or) conditional statements:
• if statement
• if...else statement (else clause with if statement)
• elseif....clause with the if statement
• switch statement
if statement: the if statement is used to controlling the execution of statements. Using if
statement to execute no of statements when ever the condition is true.
Syntax:
if(condition)
{
//Statements;
}
<?php
$a=20;
$b=10;
if ($a>$b)
echo "the biggest no=".$a;
if($b>$a)
echo “the biggest no=”.$b;
?> 31
output: the biggest no=20
S.G.S Degree College, pippara T.Ganesh M.C.A
gani.tanuku@gmail.com MySql, Php, Apache
if(condition)
{
//Statements;
}
Else
{
//statements;
Write a program Example of if..else statement:
}
<?php
$a=20;
$b=30;
if ($a>$b)
echo "the biggest no=".$a;
else
echo “the biggest no=”.$b;
?>
output: the biggest no=30
Elseif clause with if statement: the series of blocks it executes only one block executes
when the condition is true otherwise it executes else statements.
Syntax:
if(condition1)
{
//Statements1;
}
Elseif(condition2)
{
//statements2
}
Else
{
//statements3
}
32
<?php
$a=date(“d”);
if ($a==”fri”)
echo "have a nice friday”;
elseif($a==”sat”)
echo “have a nice saturday”;
else
echo “have a nice day”;
?>
The Switch statement: switch statement used to select one block of several blocks. It is a
selection statement. It executes only one block of statements and it performs matching process.
Syntax:
switch (expression)
{
case label1:
statement1;
break;
case label2:
statement2;
break;
default:
statements;
}
In above syntax, first evaluate expression and it is compared to each case label. When the
case label is match that block of code is executed. break statement is used to exit the out of
switch. Suppose there is no case label is match then executes default block.
Ex:
<?php
$n=3;
switch ($n)
{
case 1:
echo “number1”;
break;
case 2:
echo “number2”;
break;
default:
echo “no number”;
}
?>
Output: no number
33
Syntax:
Condition?expression1:expression2
First evaluate condition, if condition is true then executes expression1 otherwise executes
expression2.
Ex:
<?php
$a=20;
$b=30;
echo "the biggest no=".$a>$b?$a:$b;
?>
output: the biggest no=30
Loops:
Loops execute a block of code repeatedly until the condition is false
The loop statements are
• While statement
• Do..while
• For statement
While statement: the while loop is a entry controlled loop. It executes a group of
statements repeatedly until the condition is false.
Syntax:
While(condition)
{
//statements
}
In while loop, first execute the condition . here if the condition is true then the
group of statements executes number of times until the condition is false.
Ex: <?php
$i=1;
While($i<=10)
{
echo $i;
$i++;
}
?>
output: 1,2,3,4,……10
Do. while loop: : the do. while loop is a exit controlled loop. It executes a group
of statements repeatedly until the condition is false. But the condition is false the
do. while loop execute once.
Syntax:
Do
{
//statements
34
} While(condition);
S.G.S Degree College, pippara T.Ganesh M.C.A
gani.tanuku@gmail.com MySql, Php, Apache
Ex:
<?php
$i=1;
do{
echo $i;
$i++;
}while(i<=10);
?>
output: 1,2,3,4,……10
For statement: for loop is a entry controlled loop. It executes a group of
statements repeatedly until the condition is false.
Synetx:
Intilization part is used to declared the variables and assign the value to the
variable
Condition part is used to test the condition. The condition is true then execute body
of the loop.
Inc/dec part is used to increment or decrement the variable.
Ex:
<?php
for($i=1;$i<=10;$i++)
{
Echo $i.”times 2 is ”.($i*2).”<br />”;
}
?>
output: 1 times 2 is 2
2 times 2 is 4
3 times 2 is 6
…………….
10 times 2 is 20
Nesting for loops: A for loop internally contains other for loops that is called
nested for loop.
Example of nested for loop: write a php script to print multiplication table 1 to 10
in to a browser.
35
<?php
<?php
echo "<table border=1>";
for($y=1;$y<=10;$y++)
{
echo "<tr>";
for($i=1;$i<=10;$i++)
{
echo "<td>";
echo ($i * $y);
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
Break and continue statements: break statement is used to break out of the loop. Continue
<?phpthe loop.
statement is used to continue
Example of breakFor($a=-4; $a<=10; $a++)
statement:
{
If ($a==0)
{
break;
}
Else
{
$t=4000/$a;
Echo “4000 divided by”.$a.”is”.$t.”<br />”;
}
}
?>
Output:
36
4000 divided by -4 is -1000
4000 divided by -3 is -1333.33
S.G.S Degree College, 4000
pippara
divided by -2 is -2000 T.Ganesh M.C.A
4000 divided by -1 is -4000
gani.tanuku@gmail.com MySql, Php, Apache
In above example solve the dividing a number zero and the execution of program
does not stop using break statement.
Example of continue statement:
<?php
For($a=-4; $a<=10; $a++)
{
If ($a==0)
{
continue;
}
$t=4000/$a;
Echo “4000 divided by”.$a.”is”.$t.”<br />”;
}
?>
Output:
4000 divided by -4 is -1000
4000 divided by -3 is -1333.33
4000 divided by -2 is -2000
4000 divided by -1 is -4000
4000 divided by 1 is 4000
4000 divided by 2 is 2000
………………………….
4000 divided by 10 is 400
A php contains hundreds of built-in functions. Each and every function executed by calling the
name of function.
Calling function syntax is:
37
The calling function provides name of the function and arguments. Suppose function can not
contain arguments then we calling without argument list.
The abs() function is built-in function, and these function returns absulte value. For example
calling the abs() function is like as below
<?php
$n=-22;
$n1=abs($n);
echo $n1; // it prints 22
?>
Strtoupper() is a predefined function, this is used to convert lower case letters to upper case letters.
For example calling strupper() like as below.
<?php
$n=-“ganesh”;
$n1=strtoupper($n);
echo $n1; //GANESH
?>
Defining function:
Define the user defined function by using function statement. A function can define two types i.e
Function contain without arguments and function contain with arguments.
Function contain with out argument:
function function_name()
{
//code……
}
We define Function, it contains function name and arguments list and function body.
Example of php script with define function
<?php
Function f1() // define function without arguments
{
38
Example
<?php
Function f1($txt)
{
Echo “hello=”.$txt;
}
f1(“ganesh”); // calling function with argument
?>
o/p: hello ganesh
returning values from user-defined functions:
function returns the values to calling function by using return statement. The return statement
stops the execution of the function and value send back to calling code
example of returning value:
<?php
function add($a,$b)
{
$r=$a+$b;
return $r;
}
Echo “the result =”.add(6,5);
?>
Save the file i.e scope.php in server/apache2/htdocs folder.give the request to server i.e
http://localhost/scope.php the result is like as below
39
The value of $tvar is not printed because no variable exists outside the f1 function.
Accessing variables with global statement:
A variable declared within the php script that variable accessing all functions by using global
statement. Suppose with out global statement the local variable is can not be accessing in other
functions. Like as below
For example variable defined outside the function are inaccessible from within function
<?php
$a=200;
Function fun()
{
Echo “the value=”.$a;
}
Fun();
?>
Save the file i.e test.php in server/apache2/htdocs folder.give the request to server i.e
http://localhost/test.php the result is like as below
Suppose you want to access an variable with in a function without passing an argument by using
global statement.
The example of accessing global variables with global statement:
<?php
$a=200;
Function fun()
{
global $a;
Echo “the value=”.$a;
}
Fun();
?>
Save the file i.e test2.php in server/apache2/htdocs folder.give the request to server i.e
http://localhost/test2.php the result is like as below
<?php
function f1()
{
$n=10;
40
$n++;
echo $n."<br />";
}
f1();
f1();
f1();
?>
in above example the output is 10,10,10. here the n variable increment value is not stored between
function calls. Using the static statement we have to store the n variable increment state between
function calls like as below example.
<?php
function f1()
{
Static $n=10;
$n++;
echo $n."<br />";
}
f1();
f1();
f1();
?>
Save the file with static.php in c:/server/apache2/htdocs. Now start the server and open the
browser give the request to server i.e the url is http://localhost/static.php
o/p: 10
11
12
Passing variable references to functions:
When u pass arguments to functions, they are stored as copies in parameter variable value. If any
changes in function variables then not changes to local variables. For example like as below
<?php
function f1($a)
{
$a=$a+10;
echo "the function variable value=".$a."<br />";
}
$x=20;
f1($x);
echo "the local variable value=".$x;
?>
Output:
the function variable value=30
the local variable value=20
When u pass arguments to function by reference, they are stored as copies in parameter variable. If
any changes in function variables then changes to local variables original value. For example like
as below
<?php
41
function f1(&$a)
{
$a=$a+10;
echo "the function variable value=".$a."<br />";
}
$x=20;
f1($x);
echo "the local variable value=".$x;
?>
Output:
the function variable value=30
the local variable value=30
42
Indexed arrays:
numeric array stores each array element with a numeric index. In numeric array the index is
automatically assigned and the index will be start at 0.
syntax:
$arrayname=array(“elements list”);
$a= array(10,20,30,40);
when u create array by using array function it stores the array elements like as below
10 20 30 40
0 1 2 3
//Write a php script to create array and display the array elements
<?php
$a=array(10,20,30,40);
//display the array elements by using for loop
echo "the array elements =";
for($i=0;$i<4;$i++)
echo $a[$i]."<br />";
?>
Output: the array elements=10
20
30
40
Print_r(): this function is used to display the array elements with keys.
Syntax: print_r($arrayname);
Without using for loop display the array elements i.e
<?php
$a=array(20,30.5,”ganesh”,40);
//display the array elements by using print_r()
echo "the array elements =";
print_r($a);
?>
Output: the the array elements =Array ( [0] => 20 [1] =>
30.5 [2] => ganesh [3] => 40 )
Associative arrays:
43
An associative array, each key is associated with a value. Or the array elements are stored in
named keys i.e the array is called associative array.
syntex:
$arrayname=array(“name1”=>value1,”name”=value2,…..);
example:
$age=array(“nal”=>10,””kum”=>20,”jyo”=>30,”bhan”=>40);
when u create associative array . it stores the array elements like as below
10 20 30 40
Nal kum jyo bhan
Example of associative array
<?php
$a=array(“nal”=>10,””kum”=>20,”jyo”=>30,”bhan”=>40);
//display the array elements by using print_r()
echo "the array elements =";
print_r($a);
?>
Output: the the array elements =Array ( [nal] => 10 [kum] => 20 [jyo] =>
30 [bhan] => 40 )
An array is contains more than one array that is called multidimensional arrays.
The multidimensional arrays holds more than one series of key/value pairs. create a
multidimensional array, with automatically assigned ID keys
Syntax: $variable name=array(array(“elemnts”),array(“elemnts”)…..)
Example:
$student=array(array(“name”=>”nali”,”age”=>40,”occupation”
=>”cashier”),array(“name”=>”jyo”,”age”=>50,”occupation”=>”
<?php
business”));
$student=array(array(“name”=>”nali”,”age”=>40,”occupation”=>”ca
shier”),array(“name”=>”jyo”,”age”=>50,”occupation”=>”business”));
//display the array elements by using print_r()
Example of php script:
echo "the array elements =";
print_r($student);
//display only jyo occupation
echo $student[1][“occupation”];
?>
Output: the array elements =Array ( [0]44=> Array ( [name] => nali [age]
=> 40 [occupation] => cashier ) [1] => Array ( [name] => jyo [age] => 50
[occupation]
S.G.S Degree College,=> business ) )
pippara T.Ganesh M.C.A
jyo occupation=business
gani.tanuku@gmail.com MySql, Php, Apache
Array – functions:
There are number of array built-in functions in Php. i.e
Count(): This function is used to count the array elements and it returns the integer value.
Syntax: count($array name);
Ex: $a=array(10,20,30,40);
Echo “the array count=”. Count($a);
o/p: the array count=4
Sizeof(): this funcation is used to find the given array size.
Syntax: sizeof($array name);
Ex: $a=array(10,20,30,40);
Echo “the array count=”. sizeof($a);
o/p: the array count=4
Foreach(): The foreach statement is used to print the each element in an array.
Syntax: foreach($array name as $value)
{
……….
}
Ex: $a=array(10,20,30,”ganesh”);
Echo “the array elements=”;
Foreach($a as $value);
{
Echo $value;
}
o/p: the array elemnts=10,20,30, ganesh
Array_push(): This fuction is used to insert the one or more elements to the end of an
array.
Syntax: array_push($array name, element);
Ex: $a=array(10,20,30,40);
Array_push($a,50);
Print_r($a);
o/p: array[0=>[10] 1=>[20] 2=>[30] 3=>40]
Array_pop(): This function is used to remove the last element of an array.
Syntax: $remove element =array_pop($array name);
Ex: $a=array(10,20,30,40);
$r=Array_pop($a);
45
array_sum(): this function is used to find the sum of array elements and returns the sum of
array.
Syntax: $arrayvariable=array_sum($arrayname);
Ex: $a=array(10,20,30);
$b=array_sum($a);
Echo “the sum of array=”.$b;
o/p: 60
array_product():this function is used to find the product of given elements in an array
and it returns the product value.
46
Syntax: $arrayvariable=array_product($arrayname);
Ex: $a=array(5,10,20,);
$b=array_product($a);
Echo “the sum of array=”.$b;
o/p: 1000
47
UNIT-III
Working with objects and forms
Object is a run time entity which can hold class data i.e methods and class variables. Objects are
also called class variables.
Syntax : $object variable=new classname();
Class:
48
A Class contains object properties(data) and object methods. These methods and data are
accessing with objects.
Syntax:
Class classname
{
//variables
//object methods
}
Example:
<?php
Class myclass
{
Note: creation of method in a class by using function statement and this method is also called
object method.
Properties of objects:
A variables are declared in a class these variables are also called properties of objects. Var
keyword is used to declared the variables in a class.
Class myclass
{
Var $a=10;
Var $b=20; //properties of objects or variables
Var $c=30;
}
Example:
<?php
Class myclass
{
Var $a=10;
Var $b=20;
Var $c=30;
}
$ob=new myclass();
Echo “a value=”.$ob->a .”b value=
49 ”.$ob->b.” c value=”.$ob-
>c;
?>
S.G.S Degree College, pippara T.Ganesh M.C.A
Output: a value=10 b value= 20 c value=30
gani.tanuku@gmail.com MySql, Php, Apache
Object methods:
Methods add functionality to your objects. Methods are defined with in a class by usinf function
keyword and A class methods are accessing with objects. The -> operator is used to call the object
methods and variables.
Example:
<?php
Class myclass
{
Function hello()
{
Echo “hello php”;
}
$ob=new myclass();
<?php
$ob.hello();
Class myclass
}
{
?>
Var $a=10;
o/p: hello php.
Var $b=20;
Example: accessing class properties within a method
Function add()
{
$c=$this->a+$this->b;
Echo “the addition value=”.$c;
}
}
$ob=new myclass();
50
$ob->add();
?>
S.G.S Degree College, pippara T.Ganesh M.C.A
Output: the addition value=30
gani.tanuku@gmail.com MySql, Php, Apache
<?php
Class myclass
{
Var $a=10;
Var $b=20;
Function add( $x,$y)
{
$this->a=$x;
$this->b=$y;
$c=$this->a+$this->b;
Echo “the addition value=”.$c;
}
}
$ob=new myclass();
$ob->add(50,40);
?>
Output: the addition value=90
Constructors:
A constructor is a special method whenever class object is created then constructor will
automatically invoked. Constructor name and class name must be same.
Constructors are two types i.e
Without arguments constructor
Parameterized constructor
Syntax:
Class A
{
Function A() // with out argument constructor
{
…….
}
}
Example: without argument constrctor
51
<?php
Class A
{
Function A()
{
Echo “this is constructor”;
}
$ob =new A();
}
?>
o/p: this is constructor
Example: parameterized constructor
<?php
Class A
{
Function A($n)
{ $a=$n;
Echo “the value=”.$a;
}
$ob =new A(20);
}
?>
o/p: the value=20
Inheritance:
Inheritance means get the object properties and object methods from one class to another class.
the parent class data inherited to child class by using extends keyword.
53
printf() function is print the data directly on a browser with formatting. The printf() function
requires a string argument that is known as format control string. It also accepts additional
arguments of different types.
Syntax:
Printf(“control string”,arg1,arg2,…argn);
Example:
<?php
Printf(“%s wants % d apples”, “nalini”,10);
?>
o/p: nalini wants 10 apples+
the format control string is a special code known as a conversion specification. A conversion
specification begins with a percent symbol(%). It is used to covert the type specification and
applying formats to display the strings or data. The conversion specification is based on type
specifier.
Type specifiers:
Specifier description
<?php
$n=543;
Printf(“decimal: %d <br />”,$n);
Printf(“binary: %b <br />”,$n);
Printf(“float: %f <br />”,$n);
Printf(“string: %s <br />”,$n);
Printf(“octal : %o”, $n);
?>
o/p: decimal: 543
binary: 1000011111
flaot: 543.00
string: 543
octal: 1037
Field width specifier: The field width specifier is describe to allocate the width (spaces) of given
field on a browser. The type specifier has proceeded by the number that indicates allocate the size
of given field.
For example:
Printf (“%4d”,6);
54
Padding spacifier
o/p:
0 0 6 2
working with printf():
Sprintf() function is used to applying formatting of printed data. it is directly not printed the output
on a browser and it returns the output to another variable.
Syntax:
$return variable name=SPrintf(“control string”,arg1,arg2,…argn);
Example:
<?php
$str=SPrintf(“%s wants % d apples”, “nalini”,10);
Echo $str;
?>
o/p: nalini wants 10 apples
String manipulations of PHP: (String functions in PHP)
55
Trim(): trim() is used to cut the first and last white spaces of given string.
Syntex:
trim(“string”);
Example:
<?php
echo trim(" nalini ");
?>
Output: nalini
Strtolower(): this function is used to the given string is converting to uppercase to lower
case.
Syntex:
strtolower(“string”);
Example:
<?php
echo strtolower("LAKSHMI");
?>
Output: lakshmi
Strtoupper(): this function is used to the given string is converting to uppercase to lower
case.
56
Syntex:
strtoupper(“string”);
Example:
<?php
echo strtoupper("laskhmi");
?>
Output: LAKSHMI
Substr_replace(): this function is used to replace the substring of given string.
Syntex:
Substr_replace(“string”,”substring”, startindex, noofchars);
Example:
<?php
echo substr_replace("abcdef", ”25”, 2,2);
?>
Output: ab25ef
str_replace(): This function is used to replace all instances of a given string within another
string.
Syntex:
str_replace(“searchstr”,”replacestr”, sourcestring);
Example:
<?php
$s=”this is 2005 year and 2005 is not leap year”;
echo str_replace("2005”, “2011”, $s);
?>
Output: this is 2011 year and 2011 is not leap year.
Strrev(): The strrev() function is used to display the string in reverse order.
Syntex:
strrev(“string”);
Example:
<?php
echo str_replace("siva”);
?>
Output: avis
Explode(): this function is used to breaks up a string into an array. The explode() function
requires two arguments i.e delimiter string and source string.
Syntex:
explode(“delimiter”, sourcestring);
Example:
57
<?php
$s=”10-11-2010”;
$d = explode("-”, $s);
Echo $d[0].”-”.$d[1].”-”.$d[2];
?>
Output: 10-11-2010
Date and Time Functions in PHP:
PHP provides date() and time() functions to Display the date and time.
Time(): This function is used to display the current system date and time with unix format.
Syntax: time();
Example:
<?php
Echo time();
?>
Output: 1202082227
Date(): This function is used to display the current system date and time providing user format.
Syntax: date(”format”,timestamp);
Format argument following characters are recognized:
d it represent the day of the month with 2 digits. i.e. 01 to 31
D it represent the day of the week in 3 letter text format. i.e. sun to sat
m it represent the month in number format i.e. “01” to “12”
M it represent the month in 3 letters text format i.e. “jan” to “dec”.
y it display the year in 2 digits i.e 90.
Y it display the year in 4 digits i.e 1990
F it display the month in long textual format i.e. “january”
l it display the day of the week in long text format i.e. “Friday”
H it display the hours in 24 time format i.e. 00 to 23.
h it display the hours in 12 hours time format i.e. 01 to 12
i it display the minutes i.e 00 to 59
s it display the seconds i.e. 00 to 59
a it display the am or pm
A it display the AM or PM
Example:
Echo “the current time and date=”.Date(“ l d F Y h:i:s A”);
o/p: Friday 2 october 2010 09:51 PM
58
example:
<?php
if(checkdate(07,12,2010))
echo “it is a current date”;
else
echo “it is not a current date”;
?>
Getdate(): This function is used to get the current system date and it returns the array.
Syntax: $a=getdate();
Example:
<?php
$a=getdate();
echo “The current date=”. a[“month”].”-”.a[“wday”].”-”.a[“year”];
?>
Output: 11-01-2010.
59
<form> tag is used to create a forms in HTML. The form tag contains two attributes i.e action and
method.
<html>
<head>
<title>HTML FORM</title>
</head>
<body>
<form action=”form.php” method=”post”>
Name: <input type=”text” name=”txt1”>
Message:<br /><textarea name=”message” rows=”5” cols=”20”>
<input type=”submit” value=”send”>
</form>
</body>
</html>
<?php
$name=$_POST[“txt1”];
$msg=$_POST[“message”];
Echo “welcome”.$name.”<br />”;
Echo “your message is:”.$msg;
?>
60
Text Fields
<input type="text" > defines a one-line input field that a user can enter text into:
<form>
First name: <input type="text" name="firstname"><br />
Last name: <input type="text" name="lastname" >
</form>
the HTML code above looks in a browser:
First name:
Last name:
61
Password fileds:
<input type="password" >
defines a password field:
<form>
Password: <input type="password" name="pwd" >
</form>
the HTML code above looks in a browser:
Radio Buttons
<input type="radio">
defines a radio button. Radio buttons let a user select ONLY ONE of given choices.
<form>
<input type="radio" name="sex" value="male" > Male<br />
<input type="radio" name="sex" value="female" > Female
</form>
the HTML code above looks in a browser:
Checkboxes
Checkboxes let a user select ONE or MORE options of a limited number of choices.
Ex:
<form>
<input type="checkbox" name="vehicle" value="Bike" > I have a bike<br />
<input type="checkbox" name="vehicle" value="Car" > I have a car
</form>
The select element is used to choose one or more items from multiple select list. The user-defined
array means the multiple items insert on a one list here Adding multiple items in an array by using
select tag and option tag. Option tag is used in a select tag.
62
<html>
<form action="list.php" method="post">
Name:<input type="text" name="txt1"><br />
Products<br />:
<select name="products[]" multiple="multiple">
<option value="Nokia">Nokia</option>
<option value="LG">LG</option>
<option value="Sony">Sony</option>
<option value="Samsung">samsung</option>
</select>
<input type="submit" value="submit">
</form>
</html></html>
<?php
$name=$_POST['txt1'];
echo "welcome ".$name."<br />";
echo "your selected product is=<br />";
if(!empty($_POST['products']))
{
foreach($_POST['products'] as $value)
{
echo "<li>";
echo $value;
echo "</li>";
}
}
?>
Save form1.php in c:/server/apache2/htdocs. Now start the server and give the request to server i.e
http://localhost/form1.html look like as below
63
Type name and select the products, when ever click the submit button it display the data on
browser. Like as below figure.
To combining a php code and HTML on to a single page follow the some procedure i.e.
A file contains html tags and php tags now we have to save the file in php extension. combines a
php code by using php standard tags.
64
<html>
<pre>
<form action="message.php" method="post" >
Name: <input type="text" name="txt1">
password: <input type="password" name="psw"><br />
<input type="submit" value="send">
<?php
$name=$_POST["txt1"];
$psw=$_POST["psw"];
echo"<br />";
echo"<br />";
Echo "username ".$name."<br />";
Echo "your password is ".$psw;
?>
</form>
</pre>
</html>
Save the file in web server i.e c:\server\apache2\htdocs\ message.php. after save start the server
and give the request http://localhost/message.php and the result screen is like as below figure
Give the name and password data in a text fileds and click the send button now display the result
is like as below
Syntax
mail(to,subject,message,headers,parameters)
65
Parameter Description
to Required. Specifies the receiver address
subject Required. Specifies the subject of the email.
message Required. Defines the message to be sent. Each line should be separated with a
new line(\n). Lines should not exceed 70 characters
headers Optional. Specifies additional headers, like From, Cc, and Bcc.
parameters Optional. Specifies an additional parameters
?>
Save the sendmail.php file in a server. i.e c:\server\apche2\htdocs\sendmail.php
66
Open the browser and Now give the request to server is http://localhost/mail.html. It display the
like as below form
When ever click the send button then the mail send to given receiver. Suppose if mail successfully
send it display the mail successfully send message on browser otherwise It displays mail sending
failed like as below.
67
<?php
echo "<font size=16 color=green >";
$name=$_POST['txt1'];
echo "welcome ".$name."<br />";
echo "your selected subjects is=<br />";
if(!empty($_POST['subject']))
{
foreach($_POST['subject'] as $value)
{
echo "<li>";
echo $value;
echo "</li>";
}
}
?>
68
//write a php script to create a form , a student select the qualification option of given options
by using option button.
<?php
$name=$_POST['txt1'];
echo "welcome ".$name."<br />";
echo "your selected qualification is=<br />";
if(!empty($_POST['qual']))
{
foreach($_POST['qual'] as $value)
{
echo $value;
}
}
?>
69
The first parameter is the form's input name and the second index can be either "name", "type",
"size", "tmp_name" or "error". Like this:
<?php
echo "<font color=red size=20>";
if(($_FILES['file']['error'])>0)
{
echo "error:".$_FILES['file']['error']."u r not brows the file plz brows the
file";
echo "<br />";
}
else
{
echo "the filename :".$_FILES['file']['name']."<br />";
echo "the filesize :".$_FILES['file']['size']."<br />";
echo "the filetype :".$_FILES['file']['type']."<br />";
echo "the filepath :".$_FILES['file']['tmp_name']."<br />";
}
echo "</font>";
?>
Save the file.php file in c:\server\apache2\htdocs\. And now open the browser and give the request
is http:\\localhost\file.html it displays form like below figure
70
Here choose the file and upload the file and now it displays the output below like this:
71
UNIT-IV
Introduction to Cookies, Working with
Files and Images
72
Cookie:
A cookie is used to identify a user. A cookie is a small file that the server stores on the user's
computer. Each time the same computer requests a page with a browser, it will send the cookie
too. In php, you can create and retrieve the cookie values.
operations on cookies is:
• Create a cookie
• Retrieve a cookie
• Delete a cookie
Create a Cookie:
The setcookie() function is used to create a cookies and it accepts five arguments.
Syntax
setcookie(name, value, expire, path, domain);
In above sysntex name and value arguments is required and remaining attributes are optional.
Example 1
In the example below, we will create a cookie named "user" and assign the value "bhanu.vanumu"
to it. We also
<?php
setcookie("username","bhanu.vanumu");
?>
Note: The value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received .
Example 2
You can also set the expiration time of the cookie. it specify that the cookie should expire after one
hour:
<?php
setcookie("username","bhanu.vanumu",time()+60);
?>
Note: In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30
days).
Retrieve a Cookie Value:
73
<?php
// Print a cookie
echo $_COOKIE["user"];
?>
//Write a php script to find out the whether the cookie is set or not.
In the following example we use the isset() function to find out if a cookie has been set or not:
<?php
setcookie("username","bhanu.vanumu",time()+60);
setcookie("city", "panjavemavaram");
if(isset($_COOKIE['username']))
echo "cookie is set<br />";
else
echo "cookie is not set<br />";
?>
Whenever the client sends the request to server , the server receives the request and it process the
request and result send back to the client. Here the same client again send the request to server ,
the server does not identify same client send the another request because http protocol does not
maintain the state.
A PHP session solves this problem by allowing you to store user information on the server.
Sessions work by creating a unique id (UID) for each user.
74
Before you can store user information in your PHP session, you must first start up the session.
<?php
session_start();
?>
store and retrieve session variables is to use the PHP $_SESSION variable:
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>
Output:
Pageviews=1
we create a simple page-views counter. The isset() function checks session variable is set or not..
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
75
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
Destroying a Session
If you wish to delete some session data, you can use the unset() or the session_destroy() function.
<?php
unset($_SESSION['views']);
?>
You can also completely destroy the session by calling the session_destroy() function:
<?php
session_destroy();
?>
76
The include() function is used to embedded or include the other files into your php program.
The include() function is requires a single argument i.e file name.
Note: suppose if your included file is stored in server then you not define to path otherwise define
a “/”.
Example of included file program:
<?php
Echo “u r file is included”;
?>
Save c:\server\apache2\htdocs\myinclude.php.
Now above file is included in your program by using include(). Like as below example.
<?php
` include(“myinclude.php”);
?>
Save:c:\server\apache2\htdocs\include.php. now open the browser and give the request to server i.e
http://localhost//include.php
Save in c:/server/apache2/htdocs/include2.php
//an include file returns a value
<?php
$a=10;
$b=20;
$c=$a+$b;
Return $c; 77
?>
S.G.S Degree College, pippara T.Ganesh M.C.A
gani.tanuku@gmail.com MySql, Php, Apache
<?php
$t=1;
If($t>1)
Include(“myinclude.php”);
Else
Echo “file not included”;
?>
Validating files:
Php provides many functions to help to find out the information about files on your system.
The functions is
• File_exists()
• Is_file()
• Is_dir()
• Checking the status of a file
1. is_readable()
2. is_writable()
3. is_executable()
• filesize()
file_exists():
This function is used to find the whether the file is exists are not. The file_exists() is returns the
Boolean value. Suppose the file exists it returns true.
Synstex: File_exists(“filename”);
Example:
<?php
If (file_exists(“test.txt”))
Echo “file is exists”;
?>
File or directory:
Is_file() function is used to check whether it is a file or not. This function returns a Boolean
values.
Synstex:
Is_file(“filename”)
Example:
<?php
If (is_file(“test.txt”))
Echo “it is a file”;
78
?>
Is_dir() is used to check whether it is directory or not. This function returns a Boolean values.
Is_dir(“directoryname”)
Example:
<?php
If (is_dir(“tmp”))
Echo “ it is a directory”;
?>
is_readable(), is_writable(), is_executable():
is_readble() function is used to check whether the file is readable or not. if it is readable file then
it returns true.
Syntax:
is_readable(“filename”)
example:
<?php
If(is_readble(“test.txt”))
Echo “it is readable file”;
?>
is_writable() function is used to check whether the file is writable or not. if it is writable file then
it returns true.
Syntax:
is_writable(“filename”)
example:
<?php
If(is_writable(“test.txt”))
Echo “it is writable file”;
?>
is_executable() function is used to check whether the file is executable or not. if it is executable
file then it returns true.
Syntax:
is_executable(“filename”)
example:
<?php
If(is_executable(“test.txt”))
Echo “it is executable file”;
?>
Filesize():
This function is used to find the size of given file and it returns the size in the form of bytes.
Syntax:
filesize(“filename”)
example:
<?php
79
File operations:
• opening a file
• reading data from file
• writing data on a file
• appending data on a file
• closing a file
Syntex:
$file=fopen("filename","mode");
Example: // the file opens a read mode
<?php
$file=fopen("welcome.txt","r");
?>
Example: // the file opens a write mode
80
<?php
$file=fopen("welcome.txt","w");
?>
Example: // the file opens a appand mode
<?php
$file=fopen("welcome.txt","a");
?>
Reading data from files:
Fgets(), fread(), fgetc() functions are used to reading data from files. Here reading the data from
files up to file end of the data by using feof(). The feof() is returns true when the file data is ended
otherwise it returns false.
Fgets(): This function is used to read the data from file with line by line
Syntex: fgets(“filepointer”,bytes);
Example:
The example below reads a file line by line, until the end of file is reached:
<?php
$fp = fopen("welcome.txt", "r") ;
//Output a line of the file until the end is reached
while(!feof($fp))
{
echo fgets($fp,1024). "<br />";
}
fclose($fp);
?>
Fread():This function is used to read the data from file with the number of bytes you want to read
Syntex: fread(“filepointer”,bytes);
Example:
The example below reads a file data as number of bytes , until the end of file is reached:
<?php
$fp = fopen("welcome.txt", "r") ;
//Output a line of the file until the end is reached
while(!feof($fp))
{
echo fread($fp,16). "<br />";
}
fclose($fp);
?>
Fgetc: This function is used to read the data from character by character
Syntex: fgetc(“filepointer”);
Example:
The example below reads a file line by line, until the end of file is reached:
<?php
$fp = fopen("welcome.txt", "r") ;
//Output a line of the file until the end is reached
while(!feof($fp))
81
{
echo fgetc($fp). "<br />";
}
fclose($fp);
?>
Writing or appending to a file:
the fwrite() function writes to an open file. when u have to use fwrite(), the previous file data is
erased and write the new data. Suppose file is not exist it creates new file with data.
Syntax:
Fwrite(file pointer,”data”);
<?php
$fp = fopen("test.txt","w");
echo fwrite($fp,"Hello bsc students…..");
fclose($fp);
?>
the fputs() function writes to an open file. when u have to use fputs(), the previous file data is not
erased and append the new data with existing data. Suppose file is not exist it creates new file with
data.
Syntax:
Fputs(file pointer,”data”);
<?php
$fp = fopen("test.txt","w");
echo fputs($fp,"Hello bsc students…..");
fclose($fp);
?>
82
83
$myimage=imagecreate(150,150);
//set colors
$black=imagecolorallocate($myimage,0,0,0);
$white=imagecolorallocate($myimage,255,255,255);
$red=imagecolorallocate($myimage,255,0,0);
$green=imagecolorallocate($myimage,0,255,0);
$blue=imagecolorallocate($myimage,0,0,255);
//draw rectangle
imageRectangle($myimage,50,50,100,100,$red);
imageRectangle($myimage,100,100,200,200,$green);
//output the image to the browser
Header(“content-type: image/png”);
Imagepng($myimage);
//destroy the image
imageDestroy($myimage);
?>
Color Fill the shapes:
Php has image functions designed to fill area as well:
• ImageFilledElipse() is used to fill an elipse.
• Image FilledArc() is used to fill a arc.
• imageFilledrectangle() is used to fill a rectangle.
//write aphp script creating a new image fill the colors.
<?php
//create the canvas
$myimage=imagecreate(150,150);
//set colors
$black=imagecolorallocate($myimage,0,0,0);
$white=imagecolorallocate($myimage,255,255,255);
$red=imagecolorallocate($myimage,255,0,0);
$green=imagecolorallocate($myimage,0,255,0);
$blue=imagecolorallocate($myimage,0,0,255);
//draw rectangle
imagefilledRectangle($myimage,50,50,100,100,$red);
imagefilledRectangle($myimage,100,100,200,200,$green);
//output the image to the browser
Header(“content-type: image/png”);
Imagepng($myimage);
//destroy the image
imageDestroy($myimage);
?>
84
UNIT-V
Introduction to MySQL and Interfacing
with Databases through PHP
85
86
One-to-many:(1:M or 1:M):- A painter paints many different paintings. But many paintings
pained by one painter. there fore the relationship “PAINTER” paints “PAINTIGS” is labeled 1:M
and similarly M:1
PAINTER
PAINTS PAINTINGS
Many to many:(m:m or m;m):-an employee learn many job courses and number of courses may be learned by
many employees. There fore the relationship “EMPLOYEE” learns “COURSE” is labeled
1 NF:-A table is in 1 NF if it is doesn’t contain repeating groups and multi valued attributes.
Defines a primary key n a table.
Example:1. Remove the repeating groups
2. Define a primary key of student table. Here sno is not P.K. because sno attribute contain
duplicate values. So we have to take another attribute to form a P.K and it is ued to get the unique
records. Here the candidate primary key is Sno and CrsId. Because it is used to get the unique
records.
87
C.P.K
In above table contains 1NF but not a 2NF. Because the above table contains partial
dependency.
In above table is contains partial dependency here a units non key attributes depends on a
part of candidate key i.e. CrsId
Partial dependency:- A non key attribute is depend on a part of the candidate key it is called
partial dependency.
Ex:-
A B C
Partial dependency
Example of 2NF:-
C.P.K
In above tables contains 1NF and 2NF but it doesn’t in 3NF. Because it is contain transitive
dependency like asbelow
In above table the address non key attribute is deped on phone non key attribute so it occurs
transitive dependency.
Transitive dependency: a non key attribute is dependent on another attribute is called transitive
dependency.
Ex:
A B C D
Transitive
Example of 3NF:- removing the transitive dependency and table should be contains 2NF i.e.
C.P.K
P.K
CrsId Units
P.K
Sno Address
P.K
Phone Address
90
The p parameter indicates the maximum total number of digits that can be stored (both
to the left and to the right of the decimal point). p must be a value from 1 to 38. Default
is 18.
The s parameter indicates the maximum number of digits stored to the right of the
decimal point. s must be a value from 0 to p. Default value is 0
money Monetary data 8 bytes
float(n) Floating precision number data from -1.79E + 308 to 1.79E + 308. 4 or 8 bytes
String types:
91
92
Sql commands:
SQL stands for structured query language. User communicates with oracle server by submitting
instructions called queries.
Creation of table syntax (or using create command):
the table creation command requires
name of the table
name of the fileds:
definitions for each field
create table syntax is:
Syntax
Insert command:
insert command is used to insert the new records on a table. The basic syntax of insert is
insert into tablename (column list) values (coloumn values);
suppose the column values is string type of data u must be enclosed with single quotes and
integers do not require quotation marks.
Note: sql requires single quotes in string type of data but mysql usage of either single or double.
Example:
Insert into employee(empno,empname) values (101,’siva’);
Query ok 1 row is created.
Or
Insert into employee values (102,’ramu’,’bvrm’);
Query ok….1 row is created.
93
Select command:
Select command is used to display the table records or display the table column values.
Syntax of select command is
Select columnlist from tablename;
in above syntax columnlist is a define a columns how many column values do u want to display.
For example, I want to display two column values from employee table i.e. the query is
For example I want to display the all records from a employee table i.e. the query is
Sql>select empno,empname,address from employee;
Or
Sql>select * from employee;
Note : * means all column values from table.
94
FROM table_name
WHERE column_name operator value
Example
The following example selects all rows from the "employee" table where "address”='now':
the employee table is:
selects all rows from the "employee" table where "address”='now' the query is:
Sql> select * from employee where address=’now’;
Example2: select empno,empname rows from the “employee” table where empname=’siva’
Sql> select empno,empname from employee where empname=’siva’;
ORDER BY clause:
The ORDER BY keyword is used to sort the specified columns.
The ORDER BY keyword sort the records in ascending order by default.
If you want to sort the records in a descending order, you can use the DESC keyword.
SQL ORDER BY Syntax
SELECT column_names
FROM table_name
ORDER BY column_names ASC|DESC
Example:
Employee table i.e.
95
now we want to select all the empnames from the table above, however, we want to sort the
names.
We use the following SELECT statement:
Sql>SELECT * FROM employee
ORDER BY empname
Query ok…
96
Display the employee records whose sal between 2000 to 5000 i.e. the query is
Sql>Select * from employee where sal between 2000 and 5000;
the result is:
Like: like operator is used to compare column value with string pattern. This operator uses two
characters as wild characters in pattern matching. i.e.
% ------- matches multiple characters
_ ……. Matches single characters.
Syntax: like pattren
Example: in above employee table, display all employee records whose names start with ‘s’
Sql> select * from employee where empname like ‘s%’;
97
Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which
record or records that should be updated. If you omit the WHERE clause, all records will be
updated!
.Example
we created a table named "Persons:
FirstName LastName Age
Siva Krishna 35
Ravi Kumar 33
The following example updates some data in the "Persons" table:
Sql>UPDATE Persons SET Age = '38'
WHERE FirstName = 'siva' AND LastName = 'krishna'";
FirstName LastName Age
Siva Krishna 38
Ravi Kumar 33
98
Delete command:
The delete command is used to delete the records from a database table.
Syntax
DELETE FROM table_name
WHERE column_n ame = some_value;
Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which
record or records that should be deleted. If you ignore the WHERE clause, all records will be
deleted!
Example
Look at the following "Person" table:
FirstName LastName Age
Siva Krishna 38
Ganesh Kumar 33
The following example deletes the records in the "Person" table where LastName=’krishna’.
Sql> delete from person where lastname=”krishna”;
The result is:
FirstName LastName Age
Ganesh Kumar 33
99
Example
Result:
NOW() CURDATE() CURTIME()
2010-11-11 12:45:34 2010-11-11 12:45:34
Example:
Create table order (orderno int,ordername varchar(10), orderdate datetime NOT NULL default
now() );
Orderno ordername OrderDate
1 chesse 2008-11-11 13:23:44.657
• HEX(N_or_S):
In HEX(N_or_S) function N_or_S is a number then this function returns a string that is
representation of hexadecimal value of N
Example:
100
• LOWER(str)
The LOWER(str) function return the String. And in this String all the characters are
changed in the lowercase.
• LENGTH(str)
The LENGTH(str) function returns the length of the String in bytes. Here are the some
example of the LENGTH(str) function:
Example:
mysql> SELECT LENGTH("roseindia");
->'9'
• REVERSE(str)
The REVERSE(str) function is used to return the reverse of String.
mysql> SELECT REVERSE('HELLO'); Example:
-> OLLEH
• RTRIM(str)
The RTRIM(str) function returns the String with space characters removed.
Example :
101
SAVEPOINT :Use to specify a point in transaction to which later you can rollback.
COMMIT
To make the changes done in transactions permanent issue the COMMIT statement.
COMMIT:
COMMENT is also optional, specify this if you want to identify this transaction in data
dictionary DBA_2PC_PENDING.
Example
Commit;
ROLLBACK
To rollback the changes done in a transaction give rollback statement. Rollback restore the
state of the database to the last commit point.
Example:
Rollback;
SAVEPOINT:
Example
savepoint a;
102
savepoint b;
rollback to a;
Then row from salgrade table and dept will be roll backed. Now you can commit the row
inserted into emp table or rollback the transaction.
If you give
rollback to b;
Then row inserted into salgrade table will be roll backed. Now you can commit the row
inserted into dept table and emp table or rollback to savepoint a or completely roll backed
the transaction.
If you give
rollback;
103
Parameter Description
servername Optional. Specifies the server to connect to. Default value is "localhost"
username Optional. Specifies the username to log in with. Default value is the name of
the user that owns the server process
password Optional. Specifies the password to log in with. Default is ""
Example
In the following example we store the connection in a variable ($con) for later use in the script.
The "die" part will be executed if the connection fails:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
?>
Closing a Connection
The connection will be closed automatically when the script ends. To close the connection before,
use the mysql_close() function:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_close($con);
?>
104
Syntax
To get PHP to execute the statement above we must use the mysql_query() function. This function
is used to send a query or command to a MySQL connection.
Example
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_close($con);
?>
Create a Table
Syntax
105
We must add the CREATE TABLE statement to the mysql_query() function to execute the
command.
Example
The following example creates a table named "Persons", with three columns. The column names
will be "FirstName", "LastName" and "Age":
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
// Create table
mysql_select_db("my_db", $con);
$sql = "CREATE TABLE Persons
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
// Execute query
mysql_query($sql,$con);
mysql_close($con);
106
mysql_select_db("my_db", $con);
mysql_close($con);
?>
</body>
</html>
When a user clicks the submit button in the HTML form in the example above, the form data is
sent to "insert.php".
The "insert.php" file connects to a database, and retrieves the values from the form with the PHP
$_POST variables.
Then, the mysql_query() function executes the INSERT INTO statement, and a new record will be
added to the "Persons" table.
Here is the "insert.php" page:
107
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
Syntax
SELECT column_name(s)
FROM table_name
Example
The following example selects all the data stored in the "Persons" table (The * character selects all
the data in the table):
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
108
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
mysql_close($con);
?>
The example above stores the data returned by the mysql_query() function in the $result variable.
Peter Griffin
Glenn Quagmire
109