Anda di halaman 1dari 109

gani.tanuku@gmail.

com MySql, Php, Apache

Unit-I: Installing and configuring MYSQL, Apache and PHP

Chapter-1. Installing and configuring MYSQL

Current and future versions of MYSQL:

• MySQL 5.5 is the current development release series.


• MySQL 5.1 is the current General Availability (Production) release series.
• MySQL 5.0 is the production release series.
• The MySQL is open source and the versions are available on website is
http://www.mysql.com/downloads.
• MYSQL AB, now owned by the sun micro systems, it is responsible for creating and
distributing mysql.

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.

Release names also include a suffix. The possible suffixes are:

• alpha indicates that the release is for preview purposes only


• beta indicates that the release is appropriate for use with new development.
• rc indicates a Release Candidate. Release candidates are having all of MySQL's internal
testing.
• If there is no suffix, it indicates that is the release is a General Availability (GA) or
Production release.

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.

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Mysql installation on LINUX:

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.

Using RPM Installation of mysql:

Using RPM , it has contain two files:

 MySql- server-type-VERSIONNUMBER.PLATFORM.rpm----it is my sql server


 MySql- client-type-VERSIONNUMBER.PLATFORM.rpm----it is my sql client libraries.

To perform a minimal installation from RPMs, you can type the following at your Linux prompt
i.e

Shell>rpm – i MySQL –server-5.0.51.i386.rpm MySQL – client –5.0.51.i386.rpm

Now mysq linstallation will be started on linux..

Using Binaries Installation of mysql:

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

shell> groupadd mysql


shell> useradd -g mysql mysql

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> gunzip < /path/to/mysql-VERSION-OS.tar.gz | tar xvf -


shell> ln -s full-path-to-mysql-VERSION-OS mysql
shell> tar zxvf /path/to/mysql-VERSION-OS.tar.gz

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

4. Change location into the installation 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 bin directory contains client programs and the server.


 The scripts directory contains the mysql_install_db script. It is used to initialize
the mysql database
  mysql installation files are contains as root so change the owenership to mysql by using
following commands.

shell> chown -R mysql .


shell> chgrp -R mysql .

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:

shell> scripts/mysql_install_db --user=mysql

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:

shell> chown -R root .


shell> chown -R mysql data

8. After everything has been unpacked and installed, To start the MySQL server, use the
following command:

shell> bin/mysqld_safe --user=mysql &

After starting the server, you should set up passwords.

set the root password

Now, before you do anything else, set root user's password (!)

SELECT Host, User FROM mysql.user;


SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_password');

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

MYSQL installation on windows:

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)

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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.

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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.)

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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.

Introducing the mysql privilage system:


The mysql privilage system is always on. You can try to connect the mysql server it checks the
following three things i.e
 check the host(where you access from)
 Username and password
 Command privileges
All this information is stored in database it is automatically created when mysql is installed.
There are number of privileges in mysql database i.e
 Columns privileges: defines user privileges for particular fields in a table
 Db privileges: defines the permissions for all databases on a server
 Host privileges: defines the valid hosts that is used to connect the database.
 Procs privilages: defines user privileges for stored routines.
 Tables privileges: defines the user privileges for specific tables within the database
 User: defines the command privileges for a specific user.
The Two-step Authentication process:

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

 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

MySql>insert into jyothi values (‘’,’my test’);


Error1044: Access denied for user.

Working with user privilages:


if you are the administrator of your mysql server and you are the provide the privileges to users to
accessing the database by using grant command and revoke commands.
Adding Users:
Grant command is used to adding new users by connecting mysql database and accessing the
mysql database. the user set the privileges to access the db in particular database using grant
command.
Syntax of the grant command:
Grant privileges
On databsename.tablename
To username@host
Identified by “password”;

List of privileges provide to particular user to access the database.

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

 All-----------all common privileges gives to the user


 Alter-------user can modify the tables,columns and indexes.
 Create------create the tables and databases
 Delete------ user can delete the records from tables.
 Drop-------drop the tables and databases
 Insert------user can insert the records to the table.
 Select------user can select the records from tables.
 Update----user can updates records in table.
Suppose you want to create a user i.e user name is ravi with password of abc123 and provides a
select, insert privileges on emp table in employee database. The user able to connect the database ,
accessing the database using this command.

Grant select, insert


On employee. emp
To ravi @ ”localhost”
Identified by “abc123”;
Ex:
Shell> mysql –h localhost –u jyothi –pab123 test
Mysql> select * from emp;
The query is accepted and display this
EID Ename
1 Nalini
2 kumari

Mysql> insert into emp values (3,”bhanu”);


The query is accepted.
Mysql> drop emp;
Access is denied drop is not used.

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 the privileges:

Removing privileges instead of the grant command, you can use revoke command.

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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@”%”;

Ex: Mysql> insert into emp values (4,”kumari”);


Query not accepted….(because insert privilage is removing)
Suppose we can remove all privilages on all tables in mysql databases. The command is
Revoke All
On *.*
Fom ravi@”%”;

10

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Chapter-2. Installing and configuring Apache

Current and future versions of Apache:


If u want to download the apache httpd server then you have to visit website at
http://httpd.apache.org. in this website there are several apache versions releases i.e apache 1.3.x
and Apache 2.0.x and Apache 2.2.X versions. Here x indicates different version numbers. The
Apache 2.2 release series has contains different version numbers i.e Apache 2.2.1 and Apache
2.2.2 etc. if u want to change or downloads the apache versions , go to visit apache website i.e the
download link is http://httpd.apache.org.
Choosing appropriate installation method:
Apache is a open source. Open source means every one can access the full source code of the
software. When you visit apache software foundation website, it is contains several options of
apache installation s/w’s. suppose apache server runs on Linux/Unix platform then u better to
choose apache binary distributions. The list of binary distributions is
Httpd-2.2.3.tar.gz or httpd – 2.2.9.tar.gz or httpd- 2.3.4.tar.gz
Suppose if u want to run apache server on windows, we are go to apache website choose
installation method is (MSI Installer) win32 binary distribution. (Or ) directly download the apache
win32 distribution by using http://www.apache.org/dist/httpd/binary/win32/readme.html and
the lsit of windows binaies is
Httpd-2.2.3.win32.vc6.x86 or httpd – 2.3.2.win32.vc6.x86 etc.

Installing Apache on windows:-

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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.

11. after click next , it proceeds installation process.

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 –

Configuring Your Server for Apache:


Once you have got the files, you need to tell your machine where to find everything by
configuring the source files. i.e to accept all the defaults and type the following:

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Installing header files


Installing system files
……….
Make[1]: instlling directory ‘usr/local/apache/bin/httpd-2.2.8’.
To test the apache installation successfully or not ,type the following at the prompt
Shell> /usr/local/apache/bin/httpd –v
The output is
Server version: Apache/2.2.8
Server built: july 31 2010 10:34:11

Apache Log Files:

The Apache includes three log files by default. i.e

• 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

127.0.0.1 - - [08/Aug/2010:22:36:52 +0530] "GET / HTTP/1.1" 200 44


127.0.0.1 - - [08/Aug/2010:22:54:10 +0530] "GET /phpinfo1.php HTTP/1.1" 404 210

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

Apache Related Commands:

The apache server executes and stops also by using commands. The apache server has contain
some apache related commands i.e

13

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

[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

-k start : this command is used to start the apache server successfully


Syntax: httpd -k start
Example: c:\server\apache2\bin>httpd -k start
Apache server starting

-k stop : this command is used to stop the apache server successfully


Syntax: httpd -k stop
Example: c:\server\apache2\bin>httpd -k stop
Apache server stoping

-k restart : this command is used to restart the apache server successfully


Syntax: httpd -k restart
Example: c:\server\apache2\bin>httpd -k restart
Apache server restarted

-k uninstall : this command is used to uninstall the apache service


Syntax: httpd -k uninstall
Example: c:\server\apache2\bin>httpd -k uninstall
Apache service is successfully uninstalled.

-l : this command is used to display the list compiled modules


Syntax: httpd -l
Example: c:\server\apache2\bin>httpd -l

-v : this command is used to display the version number of apache server.


Syntax: httpd -v
Example: c:\server\apache2\bin>httpd -v
Version number : Apache /2.2.2

-L : this command is used to display the list of configuration directives


Syntax: httpd -L
Example: c:\server\apache2\bin>httpd -L

14

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Chapter-3. Installing and configuring PHP


Building PHP on Windows with Apache:

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

UNIT-II
PHP BASICS

18

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Chapter-1. Basics of PHP

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:

 Php is cross – plat form.


 Php is cross server(it means supports different types of servers).
 Php is open source technology.
 Php is extensible
 We can easily embedded VB,JSP,ASP scripts to php script.
 Php 5.0 is providing complete object oriented structure.
 Php is providing different types of security modes like authentication, authorization,
encryption etc.
 Php supports any type of databases.
 Php supports light weight editors to implement logic.
 Php is very easy to learn and develop the applications.

Client side script:-


The script is which is executing client machine is called as client side script. Client side script is
executing with the help of browser. Every browser contains interpreters to execute the client side
script.
Ex: HTML, Java Script, XML.
Server side script:
The script which execute server sends the executable code to the browser.
Ex: PHP,ASP,JSP etc.
Web server:
Web server is a software used to run the web applications. It handles the requests from client.
Ex: Apache, IIS, Tomcat etc.
Web browser:
It is software used to access the websites from web server. Ex: internet explorer, mozilla etc.
Protocols:
It is a set of instructions and transfer the information from one system to another system.
Ex: TCP/IP,http.

19

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Request: a trip of web page from client to server is called request.


Response: server sends the output to the client in the form of response.

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.]

The basics of PHP scripts:


A php scripting block always starts with <?php and ends with ?>. A php scripting block can be
placed anywhere in the document.
Syntax of php script:
<?php
…….
statemnets
20

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

…….
…….
?>

A sample php script:

<?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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

</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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Chapter-2. The Building blocks of PHP

the building blocks of php is


• Variables
• Datatypes
• Operators
• Constants
Variables:
Variables are used to store the values. All variables in PHP start with a $ sign symbol. Suppose we
can forget $ sign symbol at the beginning of variable declaration it will not work.
The syntax of variable declaration:
$var_name = value;

Php is loosly –typed language because the programmers did not provide the data types at the time
of variable declaration.

Example of creating a variable containing a string, and a variable containing a number:

<?php
$txt="Hello World!";
$x=16;
Echo $txt;
Echo $x;
?>

Output: hello world


16
Naming rules of varables:

 A variable name must start with a letter or an underscore "_".


 A variable name should not contain spaces
 We can also declared the lower case letters or upper case letters.
 A variable name should not contain any special symbols.

Types of variables in PHP:


24

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

 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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

• $_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.

Data types in PHP:

Php supports 3 types of data types i.e

 Scalar data types


 Compound data types
 Special data types.
Scalar data types: All primitive data types is called scalar data types. It contains Boolean,
integer, float or double, string.
Boolean: this data type represent true or false.
Ex:
<?php
$a=true;
Echo $a;// it prints 1
$b=false;
Echo $b //it prints null
?>
Is_bool(variable name): this function is used to test the given variable stores the Boolean or not.
Suppose the given variable stores the Boolean data it returns one otherwise it returns none.
Ex:
$a=true;
Echo is_bool($a);//it prints 1
Integer: integer variables can holds numbers. i.e {….,-2,-1,0,1,2,…….}
Ex: $a=100;//it is integer varable.
Is_int(variablename): it returns 1 (true) the variable is integer data type.
Ex: $a=100;
Echo is_int($a);//prints 1
Float: floating numbers are contains fractional parts i.e (3.57,22.90 etc)
Ex: $a=35.4(note: $a is contains float data type)
Is_float(variable): it returns one (true) when the variable stores the float value.
Ex: $a=89.9;
Echo is_float($a);//it prints one
String: sting variable can hold collection of characters with in the double quotes or single quotes.
Ex: $a= “ganesh”;
$b=’siva’;
Is_string(variable): it returns one when the variable stores the float value.
Ex: $a=”ganesh”;
Echo is_string($a);//it prints one.
Compound data types:

26

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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) Object: object is an instance of class. Class is keyword to declare a classes in php.


Syntax of object creation: $object variablename=new classnaem();
Ex: <?php
class A
{
Var $a=10;
}
$ob=new A();
Echo $ob->a; // it displays 10
?>
Special data types:
1) Resource data type: A resource variable refers the external resource like database
connections .

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

-> 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 ?

changing type with set type():


php provides settype() function, it is used to change the variable type. In this function we can pass
the variable and changed data type and separated with comma.
Syntax of set type:
Settype(variablename,’new type’);
Ex:

<?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?

Opearators and expressions: operator is a symbol it is used to perform an action and


produce a values. Php contains number of operators i.e

Arithmetic Operators: arithmetical operator performs all mathematical calculations.

Operator Name Example Result


+ Addition $x=2 4
$x+2
- Subtraction $x=2 3
5-$x
* Multiplication $x=4 20
$x*5
/ Division 15/5 3

% Modulus (division remainder) 5%2 1


10%2 0
++ Increment x=5 x=6
x++

28

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

-- Decrement x=5 x=4


x--

Assignment Operators: assignment operator is used to assign the values to variables and
expressions are assign to variables.

Operator Nam e example


= Assignment $X=10(10 is assign to x)
$y=20(20 is assign to y)
$x=($x+$y)

Comparison Operators:

comparision operator performs compare and test the given operands. It returns true or false values.

Operator Description Example


== is equal to $X=5,$y=10, $x==$y returns false
!= is not equal $x!=$y returns true
> is greater than $x>$y returns false
< is less than $X<$y returns true
>= is greater than or equal to $x>=$y returns false
<= is less than or equal to $x<=$y returns true

Logical Operators:

it is used to combines the two expressions.

Operator Description Example


&& and $x=6
$y=3

($x < 10 && $y > 1) returns true


|| or $X=6
$y=3

($x==5 || $y==5) returns false


! not $X=6
$y=3

!($x==$y) returns true

Increment and decrement operator:


increment operator is used to increase the value by one that value is assign same variable.
Decrement operator is used decrease the value by one.

29

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Operator Nam e example


++ Increment $x=10;
$x++;(it means increment the variable value by
one) it returns 11
-- Decrement $x=10;
$x--;(decrease the variable value by one)//it
contains 9

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Chapter-3. Flow Control Functions in PHP


Control functions in php:

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:

the switching flow statements in php:

• 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;
}

Write a program Example of if statement:

<?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..else statement(else clause with if statement):


if the condition is true then execute if block statements otherwise it executes else block
statements. if block is called true block and else block is called false block.
Syntax:

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
}

Write a program Example of elseif statement:

32

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

<?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

 Ternary operator: (use ? operator):


The “?:” pair is a conditional operator (or) ternary operator.

33

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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:

For (intilization; condition; inc/dec)


{
//statements
}

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

<?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

Chapter-4. Working with Functions in PHP


Function:
A function is self contained block of code that can be executed when ever called and performs a
particular task.
Functions are two types i.e built-in functions, user defined functions. Built- in functions are
already built in your php software when ever calling the function, the function code will be
executed. User defined functions are defined by the user.
Calling functions:

A php contains hundreds of built-in functions. Each and every function executed by calling the
name of function.
Calling function syntax is:

37

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Function name($arguments list);

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
{

Echo “hello function”;


}
F1(); //calling user define function
?>
o/p: hello function
function contain arguments: A function define with arguments list that is called with argument
function.
Syntax:
function function_name(arguments)
{
//code……
}

38

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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);
?>

o/p: the result=11


variable scope:
A variable declared within a function that variable accessing only with in the function. It will not
be executed outside the function or within other functions.
For example creating a variable within a function and then prints the outside the function like as
below script.
<?php
Function f1()
{
$tvar=”bsc college”;
}
Echo “this is”.$tvar.”<br />”;
?>

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

O/P: Notice error: undefined variable in


c:\server\apache2\htdocs\scope.php on line 5
This is

39

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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

O/P: Notice error: undefined variable in


c:\server\apache2\htdocs\scope.php on line 5
The value=

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

O/P: The value=200

Saving state between function calls with the static statement:

<?php
function f1()
{
$n=10;

40

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

$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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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

Chapter-5. Working with arrays in PHP


Arrays:
Def: Array is a collection of elements with same type or different types.
Syntax of array creation:
$arrayname=array(elements);
Creating array in php ny using array function. Array function is used to create the array with
passing elements.
Arrays in php has three types i.e
• Indexed arrays (or) numeric arrays
• Associative arrays
• Multidimensional arrays

42

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

 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”);

example of create indexed arrays:

$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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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 )

 multi dimensional arrays:

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Echo “the remove element =”.$r;


o/p:the remove element = 40
 Array_unshift: This function is used to Adds one or more elements to the beginning of an
array.
Syntax: array_unshift($array name, element);
Ex: $a=array(10,20,30,40);
Array_unshift($a,50);
Print_r($a);
o/p: array[0=>[50] 1=>[10] 2=>[20] 3=>[30] 4=>[40]]
 Array_shift(): This function is used to remove the first element of an array.
Syntax: $remove first element =array_shift($array name);
Ex: $a=array(10,20,30,40);
$r=Array_pop($a);
Echo “the remove element =”.$r;
o/p:the remove element = 10
 Sort(): This function is used to sorting of given elements in array.(display ascending order)
Syntax: $array variable =sort($array name);
Ex: $a=array(20,50,40,10);
$s=sort($a);
Echo “the sorting elements =”;
Print_r($s);
o/p: the sorting elements =10,20,40,50
 rsort():This function is used to sorting the elements in descending order of given array
Syntax: $array variable =rsort($array name);
Ex: $a=array(20,50,40,10);
$s=sort($a);
Echo “the sorting elements =”;
Print_r($s);
o/p: the sorting elements =5,40,20,10
 array_merge(): This function is used to combines the two given arrays.
Syntax: $arrayvariable=array_merge($array1,$array2);
Ex: $a=array(10,20,30);
$b=array(40,50,60);
$m=array_merge($a,$b);
Print_r($m);
o/p:10,20,30,40,50,60

 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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

UNIT-III
Working with objects and forms

Chapter-6. Working with Objects in PHP


Creating Objects:

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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
{

Function f1() // this is object method


{
Echo “ this is object method”;
}
}
$ob=new myclass();
$ob.f1();
?>
o/p: this is object method.

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

Example: changing object properties


<?php
Class myclass
{
Var $a=10;
Var $b=20;
Var $c=30;
}
$ob=new myclass();
$ob->a=50;
$ob->b=100;
$ob->c=150;
Echo “a value=”.$ob->a .”b value= ”.$ob->b.” c value=”.$ob-
>c;
?>
Output: a value=50 b value= 100 c value=150

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

Example: changing the value of a variable from within a method

<?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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

<?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.

Inheritances are different types i.e


Single inheritance
<?php
Multiple inheritance
Class
Multilevel A
inheritance
{ inheritance
Hierarchal
Function f1( )
{

Echo “this is base class”;


}
}
Class B extends A
{
Function f2()
{
Echo “this is child class”;
}
}
$ob=new B();
$ob->f1();
$ob->f2(); 52
?>
S.G.S Degree
Output: this isCollege, pippara
base class T.Ganesh M.C.A
This is child class
gani.tanuku@gmail.com MySql, Php, Apache

Chapter-7. Working with Strings, Dates, and Times

Formatting Strings with PHP:


You have simply printed any strings you want to display directly to the browser in their original
state. Php provides two functions i.e printf() and sprintf(), that allow you first to apply formatting,
i.e define alignment within a field and display the data to different number systems.
working with printf():

53

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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

d display the decimal numbers


b display the binary numbers.
c display the characters
s display the strings
f display the floating point numbers
o display the octal numbers
Example:

<?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);

Field width specifier

54

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Printf (“%10f and %5d”, 24, 30);


Padding output with padding specifier: The padding specifier is used to padding the spaces of
output field with 0 or space. The type specifier has proceeded by the zero or space that indicates
padding specifier.
For example:
Printf(“% 04d”,62);

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)

 strlen():The strlen() function is used to find the length of a given string.


syntex:
strlen(“string”);
Example:
<?php
echo strlen("Hello world!");
?>
Output: 12
 strstr(): This function is used to whether check the substring of given string. if substring
is found it returns remaining string otherwise it returns false.
syntex:
strstr(“string”,”substring”);
Example:
<?php
echo strstr("bhanu reka",”bhanu”);
?>
Output: bhanu reka
Example
<?php
echo strstr("bhanu reka",”nalini”);
?>

55

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Output: false[does not print any output]


 Strpos(): This function is used to returns the substring position of a given string. If a match
is found, it return the position of the first charcter. If no match is found, it will return
FALSE.
Syntex:
strpos(“string”,”substring”);
Example:
<?php
echo strstr("bhanu reka",”reka”);
?>
Output: 6
 Substr(): This function is used to display the substring of a given string.
Syntex:
substr(“string”,startindex, number of chars);
Example:
<?php
echo substr("bhanu reka",6,4);
?>
Output: reka

 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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

<?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

timestamp argument is provide future and past time by using mktime().


Mktime(): this is used to display the future and past date and time.
Syntax: mktime(h,m,s, mon,day,year);
Example:
Echo Date(“l ”,mktime(0,0,0,11,01,2010));// friday
echo date(“m-d-Y”,mktime(0,0,0,07,01,2010));//07-01-2010
checkdate():
This function is used to check the date is current system date or not and it returns the true or false.
syntax: checkdate(m,day,year);

58

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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.

Chapter 8: Working with Forms in PHP

Creating a simple input form:


Forms are used to provide the data or input on your program. a form contains no of input fields,
these input fields is used to provide data to php code. Forms are created by using HTML language.

59

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

<form> tag is used to create a forms in HTML. The form tag contains two attributes i.e action and
method.

And forms are contains different types of input fields.


The input tag is <input> accepts different types field types .i.e.
<input >----------this tag is create a input tag. Input tag contains type attribute.
Type=”text”--------it creates text box
Type=”submit”……it creates submit button
Type=”password”…. It creates the password field.
Type=”checkbox”….it creates the chekboxes.
Method values are two types i.e. Get method and post method. The get method and post method is
used to send the form data.
Get: Appends the form-data to the URL and less amount of data is send. The data security is less.
Post: it sends the body of the data and large amount of data is send. The data security is more.

A simple html form is:

<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>

Save the form.html in your webserver i.e c:\server\apache2\htdocs\form.html.


Here The form is contains text filed with name txt1 and text area with the name message, and it is
contains send submit button.
The form data accessing in php program here it is two global variables are used i.e. $_POST,
$_GET
$_POST: This variable is used to access the post method values.
$_GET: This variable is used to access the get method values.

Reading input from a form:

<?php
$name=$_POST[“txt1”];
$msg=$_POST[“message”];
Echo “welcome”.$name.”<br />”;
Echo “your message is:”.$msg;
?>

60

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

save the form.php file in web server i.e. c:\server\apache2\htdocs\form.php


now start the server and open the browser give the request to http://localhost/form.html
now it display the form below like this
input form:

The output is:

Create a different types of input fields in HTML:


Text Fields

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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:

Password: (note password data is astrick symols)

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.

<input type="checkbox" />

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 HTML code above looks in a browser:

Accessing form input with user-defined Arrays:

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Syntex of select tag:


<Select name=”products” multiple=”multiple”>
Adding elements in list by using option tag
Syntex og option tag:
<option value=”value1”>value1</option>
Example of accessing form input with user defined arrays:
Creating html form:

<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>

Save the form1.html in c:/server/apache2/htdocs/ .


Accessing form input data:

<?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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Type name and select the products, when ever click the submit button it display the data on
browser. Like as below figure.

Combining HTML and php code on a single page:

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

<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

Sending mail on form submission:

The PHP mail() function is used to send emails froms.

Syntax

mail(to,subject,message,headers,parameters)

65

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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

Example of creation of mail creation form in html:


<<html>
<center><h1>sending mail</h1></center>
<body>
<form action="sendmail.php" method="post">
TO <input type="text" name='txtEmailto' size=30><br />
Subject <input type="text" name='txtsub' size=25><br />
From <input type="text" name='txtEmailfrm' size=25><br />
<b>Message Body</b><br />
<textarea name='txtmsg' rows="10" cols="25"></textarea><br />
<input type="submit" name="submit" value="send" size=12>
</form>
</body>
</html>

Save the mail.html in server. i.e c:\server\apache2\htdocs\maill.html .


Creating script to send mail:
<?php
//Check whether the submission is made

//Declarate the necessary variables


$mail_to=$_POST['txtEmailto'];
$mail_from=$_POST['txtEmailfrm'];
$mail_sub=$_POST['txtSub'];
$mail_mesg=$_POST['txtMsg'];

//Check for success/failure of delivery


if(mail($mail_to,$mail_sub,$mail_mesg,$mail_from))
echo "E-mail has been sent successfully from $mail_from to
$mail_to";
else
echo "Failed to send the E-mail from $mail_from to $mail_to";

?>
Save the sendmail.php file in a server. i.e c:\server\apche2\htdocs\sendmail.php

66

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Some Example scripts of forms in php:


//write a php script to create a form , a student select the numbar of subjects in given
subjects by using check boxes.

Create a form in html:


<html>
<body>
<font color ="red">
<form action="check.php" method="post">
Name<input type="text" name="txt1"><br />
SELECTED BSC SUBJECT<br />
<input type="checkbox" name="subject[]" value="maths">mathematics
<input type="checkbox" name="subject[]" value="physics">physics
<input type="checkbox" name="subject[]" value="computers">computerscience
<input type="checkbox" name="subject[]" value="electronics">electronics
<input type="checkbox" name="subject[]" value="statastics">statastics<br />
<input type="submit" value="submit">
</form>
</font>
</body>
</html>

Accessing form input data:

<?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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

//write a php script to create a form , a student select the qualification option of given options
by using option button.

Crating form in html:


<html>
<body>
<font color ="red">
<form action="radio.php" method="post">
Name<input type="text" name="txt1"><br />
<b>select qualification</b><br />
<input type="radio" name="qual[]" value="INTERMEDIATE">INTERMEDIATE
<input type="radio" name="qual[]" value="DEGREE">DEGREE
<input type="radio" name="qual[]" value="Msc">Msc
<input type="radio" name="qual[]" value="MCA">MCA
<input type="radio" name="qual[]" value="MBA">MBA<br />
<input type="submit" value="submit">
</form>
</font>
</body>
</html>

Accessing form input:

<?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;

}
}
?>

WORKING WITH FILE UPLOADS:


File upload concept is used to upload the files to the server. By using the super global $_FILES
array you can upload files from a client to server.
These fields are described in the below table: i.e.

69

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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:

• $_FILES["file"]["name"] - the name of the uploaded file


• $_FILES["file"]["type"] - the type of the uploaded file
• $_FILES["file"]["size"] - the size of uploaded file
• $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the
server
• $_FILES["file"]["error"] - the error code [note: file not uploade it provides >0 otherwise it
provides <0

Creating the file upload form:


First you must create the html form to handle the upload. Html forms include the file upload fields
must include an ENCTYPE argument.
ENCTYPE=”multipart/form-data”.
create an input element of file by using “file” argument of input type attribute . like as below code
to create file upload form in html and save the c:\server\apache2\htdocs\file.html
<html>
<form action="file.php" method="post" enctype="multipart/form-data">
Upload file name <input type="file" name="file1"><br />
<input type="submit" value="upload">
</form>
</html>

Accessing the file upload data:

<?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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Here choose the file and upload the file and now it displays the output below like this:

71

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

UNIT-IV
Introduction to Cookies, Working with
Files and Images

72

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Chapter 8: Working with Cookies and User Sessions

Working with Cookies:

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

The PHP $_COOKIE variable is used to retrieve a cookie value.


In the example below, we retrieve the value of the cookie named "user" and display it on a page:

<?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 />";

?>

//to print all cookies on browser


<?php
print_r($_COOKIE);
?>
o/p: bhanu.vanumu
panajavemavaram
How to Delete a Cookie?
If u want to delete the cookie , then u will use the time() function with - symbol.
Delete example:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>

Working with sessions:


A PHP session is used to store information on server. Session variables hold information about one
single user, and are available to all pages in one application.

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Starting a PHP Session

Before you can store user information in your PHP session, you must first start up the session.

Note: The session_start() function used to start the session.

<?php
session_start();
?>

Storing a Session Variable

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

// w.a php script to create a simple page view counter.

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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.

The unset() function is used to delete the session data:

<?php
unset($_SESSION['views']);
?>

You can also completely destroy the session by calling the session_destroy() function:

<?php
session_destroy();
?>

76

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Chapter 9: Working with Files

Including Files with include():

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

o/p: u r file is included

Returning a value from an included document:


Included files can return a values by using return statement and it returns the value when you
include the file.
Example:
//include another file
<?php
` $sum=include(“sum.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

Using include() within control structures:


Include() function is also using control structures i.e. if..else, for, while. In if…else statement , if
the condition is true then the file will be included otherwise not.
Example

<?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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

?>

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

Echo “The file size=”.filesize(“test.txt”);


?>

79

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Creating files and deleting files:


In php, Creating files by using touch() function and deleting the files by using unlink() function.
Touch(): This function is used to create the empty file in server.
Syntax: touch(“newfilename”);
Example:
<?php
If(Touch(“test1.txt”))
Echo “file is created”;
?>
Unlink(): this function is used to delete the files.
Syntax: unlink(“filename”);
Example:
<?php
If(unlink(“test1.txt”))
Echo “file is deleted”;
?>
File operations (or) opening a file for writing, reading or appending:

File operations:
• opening a file
• reading data from file
• writing data on a file
• appending data on a file
• closing a file

opening a file: The fopen() function is used to open files in PHP.


The first parameter of this function contains the name of the file to be opened and the second
parameter specifies in which mode the file should be opened:

The file may be opened in one of the following modes:


Modes Description
r Read only. Starts at the beginning of the file
r+ Read/Write. Starts at the beginning of the file
w Write only. Previous data is erased ,when new data is writing.
a Append. Write continue the previous data 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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

<?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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

{
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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Chapter 10: Working with images


How to create images in php:
the basic php function is used to create a new image is called imagecreate(), but creating image is
not a simple as just calling the function.
Creating image is stepwise process and include different php functions. i.e. the process is
• Creating image area
• Drawing the shapes or images
• Fill the shapes
• Converting the image file type
• Destroy the image
Drawing a new image:
Creating an image begins with the image create() function, but In this function is set the canvas
area for new image. The following line creates a drawing area that is 150 pixels width and 150
pixels height.
$myimage=imagecreate(150,150);
if u want to define a few colors of new image by using imagecolor allocate() function. Here the
following examples define five such colors, using the imagecolor allocate() and RGB values:
$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);

drawing shapes and lines:


The number of php functions are used to drawing the shapes and lines on canvas area.
• ImageElipse() is used to draw the elipse
• ImageArc() is used to draw the arc.
• ImagePolygon() is used to draw the polygon.
• ImageRectangle() is used to draw the rectangle.
• Imageline() is used to draw the line.
For example draw the rectangle on the drawing area beginning at point (50,50) and ending at
(100,100), the rectangle lines will be drawn with the color red, i.e. using the variable is $red.
Ex: imageRectangle($myimage,50,50,100,100,$red);
For example draw the line it also requires 6 arguments i.e. drawing area,(x1,y1) axes,(x2,y2) axes.
Ex: imageline($myimage,50,50,50,100,$red);

//write aphp script creating a new image


<?php
//create the canvas

83

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

$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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

UNIT-V
Introduction to MySQL and Interfacing
with Databases through PHP

85

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Chapter 11: Understanding the database design process

Database: A database is a collection of interrelated data. (or) A data base is acolection of


enduser data and metadata.
The basic operations are performed in the database is
1. insert
2. update
3. delete
4. select
User can access operations on the database using DBMS softwares. Most of the having fecilities
are
1. creating database
2. inserting data into database
3. updatig datainto database
4. deleting data from database
5. select data from database

The few DBMS S/W available in the market is ORACLE


MY SQL
SQL SERVER
DB2
SY BASE
INGRESS

Types of table relationships:-


Rlationship: relationship describes on associates among entities .for example a relationship
provides between customer and supplier . a supplier can supplies many customers and each
customer may be served by one supplier . data models are used to provide relationship b/w two
entities
• One-to-one
• One-to-many
• Many-to-many
one-to-one(1:1 (or) 1..1):- A company management many requires each employee manages only a
single store. Similarly each store managed by single employee. There fore the relationship
“EMPLOYEE” manages “STORE” is labeled 1:1

EMPLOYEE MANAGES STORE

86

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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

EMPLOYEE LEARNS COURSE

NORMALIZATON:- Normalization is the analysis of functional department b/w attributes or


data items. It reduces the redundancy data and data anomalies(i.e. insert,update,delation, anomalies
). Normalization process is improve the storage efficiency, data integrity. There are different level
of normalization as listed below..

1. first normal form


2. second normal form
3. third normal form

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

Sno Sname CrsId Units Phone Address

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.

Sno CrsId Sname Units Phone Address

87

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

C.P.K

In above table contains 1NF but not a 2NF. Because the above table contains partial
dependency.

Sno CrsId Sname Units Phone Address

C.P.K 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

2NF:- A table is in 2NF ifit is 1NF and it is no partial dependency .


Functional dependency:- A non key attribute is depend on one key attribute i.e called
functional dependency.

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:-

Sno CrsId Sname Units Phone Address


88

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

(All attributes depends on Sno, CrsId)

C.P.K

CrsId Units (units attribute fully depends on CrsId attribute)

In above tables contains 1NF and 2NF but it doesn’t in 3NF. Because it is contain transitive
dependency like asbelow

Sno CrsId Sname Phone Address

In above table the address non key attribute is deped on phone non key attribute so it occurs
transitive dependency.

3NF:- A table is in 3NF if it is 2NF and it is no 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.

Sno CrsId Sname


89

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

C.P.K

P.K
CrsId Units

P.K
Sno Address

P.K

Phone Address

In above table has contains 1NF and 2NF and 3NF

90

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Chapter 11: basic SQL Commands


Mysql data types:
mysql contains different types of data types i.e.
• numeric data types
• date and time types
• string types
numeric data types:
mysql uses all the standard ANSI SQL numeric data types. i.e.
Number types:
Data type Description Storage
smallint Allows whole numbers between -32,768 and 32,767 2 bytes
int Allows whole numbers between -2,147,483,648 and 2,147,483,647 and it accepts 4 bytes
signed and unsigned numbers.
decimal(p,s) It allows decimal numbers. Defining the display length (p) and the number of decimals 5-17 bytes
(s) is required.

s must be a value from 0 to p. Default value is 0


numeric(p,s) Fixed precision and scale numbers. 5-17 bytes

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

The n parameter indicates whether the field should hold 4 or 8 bytes


real Floating precision number data from -3.40E + 38 to 3.40E + 38 4 bytes

Date and time types:


Data type Description Storage
datetime Date and time combination in yyyy-mm-dd hh:mm:ss format. 8 bytes
date Store a date only in YYYY-MM-DD format. 3 bytes
time Stores a time in HH:MM:SS format 3-5 bytes
timestamp Stores a unique number that gets updated every time a row gets created or modified.
The timestamp value is based upon an internal clock and does not correspond to real
time. Each table may have only one timestamp variable

String types:

91

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Data type Description Storage


char(n) A Fixed-length character string between 1 and 255 characters n
varchar(n) A Variable-length character string between 1 and 255 characters
Text or BLOB A Variable-length character string. Maximum 2GB of text data
LONGBLOB A BLOB or text column with maximum length of 4 gb. Of data.

92

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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

CREATE TABLE table_name


(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)

Example: create table employee(empno int,empname varchar(10),address varchar2(10));


Quary ok…..student table created.
Example: create table student(stuno int,sname varchar(10),address varchar2(10));
Quary ok…..student table created
Mysql>desc employee;

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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

Sql>Select empno,empname from employee;

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.

Clauses in mysql (clauses are used in select command):


Clauses are used in select command. Clauses are used to help get the particular records.
Clauses
• Where
• Order by
• Distinct
Where clause:
The WHERE clause is used to filter records. The WHERE clause is used to extract only those
records that fulfill a specified criterion.
Syntax
SELECT column_name(s)

94

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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…

ORDER BY DESC Example


Now we want to select all the employees from the table above, however, we want to sort the
persons descending by their emp name.
We use the following SELECT statement:
Sql>SELECT * FROM employee
ORDER BY empname DESC
The result is:

Using Operators in where clauses:


Operators in sql is:
• Arithmetic operators i.e. +,-, / , %
• Comparision operators
• Logical operators
• Special operators
The logical operators is and , or , not

96

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

the basic comparison operators is


Operator Meaning
= Equal to
!= Not equal to
<= Less than equal to
>= Greater than equal to
> Greater than

But sql has contain some of special operators is i.e.


• Between
• Like
• Is
• In, etc.
Between operator is used to compare column value with range of values.
Syntax: between value1 and value2
Not between value1 and value2
Examples: the employee table is

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

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Is operator: Is operator is used to compare the column value is null or not.


Syntax: is null
Is not null
Example: display the employee records whose employee address in null

Sql> select * from employee where address is null


Empno empname address
101 siva NULL

Update Data In a Database


The UPDATE statement is used to update existing records in a table.
Syntax
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

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

Sql>UPDATE Persons SET firstname = 'ganesh'


WHERE FirstName = 'ravi';

98

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

FirstName LastName Age


Siva Krishna 38
ganesh Kumar 33

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

For example delete all records from a person tables.


Sql> delete from person ;
All records are deleted.
MySQL Date and Time Functions
Mysql has contains number of date and time functions. It is used to manipulate time and date data.
It also specifies the time and date formats.
The date and time functions in mysql:
Function Description
NOW() Returns the current date and time
CURDATE() Returns the current date
CURTIME() Returns the current time
DATE() Extracts the date part of a date or date
EXTRACT() Returns a single part of a date/time
DATE_ADD() Adds a specified time interval to a date
DATE_SUB() Subtracts a specified time interval from a date
DATEDIFF() Returns the number of days between two dates
DATE_FORMAT() Displays date/time data in different formats

99

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

NOW() returns the current date and time.


Syntax
NOW()

Example

The following SELECT statement:


SELECT NOW(),CURDATE(),CURTIME();

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

String functions in MySQL:


These functions can be used to manipulate the string data. The string functions in my sql i.e.
• CONCAT(str1, str2..):
The CONCAT(str1, str2….) function can have one or more arguments and its returns a
string. But if any argument is NULL then it also returns NULL.
Example:
mysql> SELECT CONCAT('In', 'd', 'ia');
-> 'India'
mysql> SELECT CONCAT('my', NULL, 'ql');
-> NULL
mysql> SELECT CONCAT(10.3);
-> '10.3'

• 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:

mysql> SELECT HEX(10);


-> 'A'
mysql> SELECT HEX( 'abd');
-> 616264

100

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

• LOWER(str)
The LOWER(str) function return the String. And in this String all the characters are
changed in the lowercase.

mysql> SELECT LOWER('ROSEINDIA');


->'roseindia'
• UPPER(str)
The UPPER(str) function return the String. And in this String all the characters are changed
in the upper case.

mysql> SELECT UPPER('ROSEINDIA');


->'roseindia'

• 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 :

mysql> SELECT RTRIM ('rose ');


->'rose'

101

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Chapter 12: Transaction and stored procedures in MySQL


Transactions:
Transaction control statements manage changes made by DML statements.
A transaction is a set of SQL statements which Oracle treats as a Single Unit. i.e. all the
statements should execute successfully or none of the statements should execute.
To control transactions Oracle does not made permanent any DML statements unless you
commit it. If you don’t commit the transaction and power goes off or system crashes then
the transaction is roll backed.
COMMIT: Make changes done in transaction permanent.

ROLLBACK: Rollbacks the state of database to the last commit point.

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.

The syntax of COMMIT Statement is

COMMIT:
COMMENT is also optional, specify this if you want to identify this transaction in data
dictionary DBA_2PC_PENDING.

Example

Insert into emp (empno,ename,sal) values (101,’Abid’,2300);

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:

Delete from emp;

Rollback;
SAVEPOINT:

Specify a point in a transaction to which later you can roll back.

Example

insert into emp (empno,ename,sal) values (109,’Sami’,3000);

savepoint a;

102

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

insert into dept values (10,’Sales’,’Hyd’);

savepoint b;

insert into salgrade values (‘III’,9000,12000);

Now if you give

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;

Then the whole transactions is roll backed.


If you give
commit;
Then the whole transaction is committed and all savepoints are removed.

Chapter 13: Intracting with MySQL using PHP

103

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Create a Connection to a MySQL Database


Before you can access data in a database, you must create a connection to the database.
In PHP, this is done with the mysql_connect() function.
Syntax
mysql_connect(servername,username,password);

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);
?>

Php Create Database and Tables:


Create a Database

The CREATE DATABASE statement is used to create a database in MySQL.

104

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

Syntax

CREATE DATABASE database_name

To get PHP to execute the statement above we must use the mysql_query() function. This function
is used to send a query or command to a MySQL connection.

Example

The following example creates a database called "my_db":

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

if (mysql_query("CREATE DATABASE my_db",$con))


{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}

mysql_close($con);
?>

Create a Table

The CREATE TABLE statement is used to create a table in MySQL.

Syntax

CREATE TABLE table_name


(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)

105

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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);

Insert Data Into a Database Table or (Working with mysql data)


The INSERT INTO statement is used to add new records to a database table.
Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their values:
INSERT INTO table_name
VALUES (value1, value2, value3,...)
The second form specifies both the column names and the values to be inserted:

106

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)
To get PHP to execute the statements above we must use the mysql_query() function. This
function is used to send a query or command to a MySQL connection.
Example
The following example adds two new records to the "Persons" table:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

mysql_query("INSERT INTO Persons (FirstName, LastName, Age)


VALUES ('Peter', 'Griffin', '35')");

mysql_query("INSERT INTO Persons (FirstName, LastName, Age)


VALUES ('Glenn', 'Quagmire', '33')");

mysql_close($con);
?>

Insert Data From a Form Into a Database


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

<form action="insert.php" method="post">


Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>

</body>
</html>
When a user clicks the submit button in the HTML form in the example above, the form data is
sent to "insert.php".
The "insert.php" file connects to a database, and retrieves the values from the form with the PHP
$_POST variables.
Then, the mysql_query() function executes the INSERT INTO statement, and a new record will be
added to the "Persons" table.
Here is the "insert.php" page:

107

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

$sql="INSERT INTO Persons (FirstName, LastName, Age)


VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

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

mysql_close($con)
?>

Retrieving data with php:

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

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);

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

108

S.G.S Degree College, pippara T.Ganesh M.C.A


gani.tanuku@gmail.com MySql, Php, Apache

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.

The output of the code above will be:

Peter Griffin
Glenn Quagmire

---------- THE END-----------

109

S.G.S Degree College, pippara T.Ganesh M.C.A

Anda mungkin juga menyukai