0% found this document useful (0 votes)
34 views

Open Source Lab Manual

Uploaded by

Hari Haran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Open Source Lab Manual

Uploaded by

Hari Haran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

IMPLEMENTATION OF BASIC LINUX COMMANDS

Ex.No: 1a

AIM
To execute various basic LINUX commands..

DESCRIPTION

Linux is well-known as a stable and reliable platform, providing database and


trading services for companies like Amazon, the well-known online bookshop, US Post
Office,and the German army. The LINUX operating system is built around the concept of
a filesystem which is used to store all of the information that constitutes the long-term
state of the system. This state includes the operating system kernel itself, the executable
files for the commands supported by the operating system, configuration information,
temporary workfiles, user data, and various special files that are used to give controlled
access to system hardware and operating system functions.
Linux Virtual File System
What is its utility? Linux can be run as a process under Windows, etc.?
• Versatile and powerful file handling facility, designed to support a wide variety of file
management systems and file structures.
• VFS presents a single, uniform file system interface to user processes.
• It defines a common file model that is capable of representing any conceivable file
system’s general feature and behavior.
• Assumes files are objects in a computer’s mass storage that share basic properties
regardless of the target file system or the underlying processor hardware.
• Files have symbolic names that allow them to be uniquely identified within a specific
directory in the file system.
• A file has several properties including an owner, protection against unauthorized access or
modification.
Linux Swap
The Linux swap partition is something you generally create once and then forget
about. This is an amount of disk space in which Linux temporarily writes data from RAM
to free up memory for other processes. The swap partition is different from all others in
that it is not used to store files in, so it won't be dealt with in any further detail here.
Windows and OS/2 partitions FAT partitions (vfat) FAT16 was the standard partition type

1
up to Windows 95, and FAT32 partitions are the standard with Windows 98. FAT16
partitions are supported by all versions of Windows, while FAT32 is supported by
Windows95 second edition onwards, and Windows 2000 onwards (but is not supported in
Windows NT). Linux supports both reading from, and writing to FAT16 and FAT32
partitions. Their main use in a Linux context is to share files between Linux and Windows
on a dual-boot system. However note that these filesystems are unable to hold information
such as file owners and permissions. FAT16 partitions are limited to a maximum of 2Gb.
Although the theoretical maximum size for FAT32 is 8 TB, Windows98's scandisk only
supports 128Gb, and Windows2000 does not permit the creation of FAT32 disks larger
than 32Gb.

BASIC LINUX COMMANDS

Simple Commands:

$who am i: Displays the current user name


$pwd: Displays the current directory
$mkdir dirname: Create new directory
$cd dirname: Changes the directory.
$cd: To exit the directory
$echo”msg”: Prints the message

CAT Commands:

$cat> filename:To create a new file


$cat filename:To view already existing file contents
$vi filename:To edit the file
$bc:Basic calculator
$script:To retrive the previously used commands
$exit:To exit from unix

Delete Commands:

$rm-I filename:To delete specified file


$rm-r dirname: To delete specified directory

List Commands:

$ls: To list the files with all its attributes


$ls-t: To list the filenames only
$ls-d: To list the directories only
$ls-c: To list the filenames in alphabetical order
$ls a*: To list the filenames starting with alphabet a
$ls *a: To list the filenames ending with letter a
$ls-x: To list the filenames columnwise

2
$ls-l: To list the filenames pagewise

Move Commands:

$mv srcfile destfile: To move source file to destination file.


$mv file dirname: To move file into specified directory.
$cp srcfile destfile: To copy source file into destination file.

Date Commands:
$date: Displays the current date.
$date +%m: Displays the current month in numbers.
$date +%h: Displays the current month in characters.
$date +%y: Displays the current year.
$date +”%H %M %S”: Displays the time in hour, minutes and seconds.
$cal: Displays the calendar.

Save and Edit Commands:


Press<Esc> and then:
:w- To save the file.
:wq- To save and quit the file.
:q- To quit.
:sh- To exit from shell programming.

Word Count Commands:

$wc filename: Display number of words, lines and characters in a file.


$wc –w filename: List the number of words in the file.
$wc –i filename: List the number of lines in the file.
$wc –c filename: List the number of characters in the file.

GREP Commands:
$grep pattern filename: Search the pattern or keyword present in the file.
$grep -c pattern filename: Displays the number of times the pattern or keyword is present
in the file.
$grep pattern file1 file2: Displays the file with pattern or keyword is present in the file.
$grep -i pattern filename: Displays the filename if the pattern or keyword is present in
the file.
$grep -n pattern filename: Displays the line numberof the pattern or keyword is present
in the file.
$grep -v pattern filename: Displays the non-occurrence of the pattern or keyword in the
file.

Sort commands:
$sort filename: sort the given file
$ sort –r filename: removes the sorting of given file.
$ sort –m filename1 filename2: merge the two files while sorting.

3
$ sort –u filename3 filename1 filename2 :merge the two file while sorting and store in
file3 without any duplication.

Head and tail commands:

$ head –no filename: display the number of lines from the file
$ tail +no filename: display from the nth line

Link commands:

$ ln filename1 filename2: saving the existing file filename1 in new filename2

4
5
SIMPLE SHELL PROGRAMMING
Ex.No: 1b

AIM
To write the shell programming using the command syntax, simple functions and
basic tests.

DESCRIPTION

What is a Shell Script


 A text file containing commands which could have been typed directly into the
shell.
There is no difference in syntax between interactive command line use and placing
the commands in a file. Some commands are only useful when used interactively
(e.g. command line history recall) and other commands are too complex to use
interactively.
 The shell itself has limited capabilities -- the power comes from using it as a "glue"
language to combine the standard Unix utilities, and custom software, to produce a
tool more useful than the component parts alone.
 Any shell can be used for writing a shell script. To allow for this, the first line of
every script is:
#!/path/to/shell (e.g. #!/bin/ksh).
The #! characters tell the system to locate the following pathname, start it up and
feed it the rest of the file as input. Any program which can read commands from a
file can be started up this way, as long as it recognizes the # comment convention.
The program is started, and then the script file is given to it as an argument.
Because of this, the script must be readable as well as executable. Examples are
perl, awk, tcl and python.
 Any file can be used as input to a shell by using the syntax:
ksh myscript
 If the file is made executable using chmod, it becomes a new command and
available for use (subject to the usual $PATH search).
chmod +x myscript
A shell script can be as simple as a sequence of commands that you type regularly. By
putting them into a script, you reduce them to a single command.
Why use Shell Scripts
 Combine lengthy and repetitive sequences of commands into a single, simple
command.
 Generalize a sequence of operations on one set of data, into a procedure that can be
applied to any similar set of data.
(e.g. apply the same analysis to every data file on a CD, without needing to repeat
the commands)
 Create new commands using combinations of utilities in ways the original authors
never thought of.
 Simple shell scripts might be written as shell aliases, but the script can be made
available to all users and all processes. Shell aliases apply only to the current shell.
 Wrap programs over which you have no control inside an environment that you can
control.

6
e.g. set environment variables, switch to a special directory, create or select a
configuration file, redirect output, log usage, and then run the program.
 Create customized datasets on the fly, and call applications (e.g. matlab, sas, idl,
gnuplot) to work on them, or create customized application commands/procedures.
 Rapid prototyping (but avoid letting prototypes become production)
Basic sh script syntax
The most basic shell script is a list of commands exactly as could be typed
interactively, prefaced by the #! magic header. All the parsing rules, filename wildcards,
$PATH searches etc., which were summarized above, apply.

In addition:
# as the first non-whitespace character on a line
flags the line as a comment, and the rest of the line is completely ignored. Use
comments liberally in your scripts, as in all other forms of programming.
\ as the last character on a line
causes the following line to be logically joined before interpretation. This allows
single very long commands to be entered in the script in a more readable fashion.
You can continue the line as many times as needed.
This is actually just a particular instance of \ being to escape, or remove the
special meaning from, the following character.
; as a separator between words on a line
is interpreted as a newline. It allows you to put multiple commands on a single line.
There are few occasions when you must do this, but often it is used to improve the
layout of compound commands.
Shell Variables
Scripts are not very useful if all the commands and options and filenames are
explicitly coded. By using variables, you can make a script generic and apply it to different
situations. Variable names consist of letters, numbers and underscores ([a-zA-Z0-9_],
cannot start with a number, and are case sensitive. Several special variables (always
uppercase names) are used by the system -- resetting these may cause unexpected
behaviour. Some special variables may be read-only. Using lowercase names for your own
variables is safest.
.
PROGRAM

Electricity bill:
Program:
echo “enter your name”
read name
echo “enter the units”
read a
if [ $a –le 100 ]
then
expr $a \* 80 \ 100
elif [ $a –le 500]
then
b=`expr $a -100`
s=`expr $b \* 150 \ 100`
expr $s +80
else

7
A=`expr $a -500`
s=expr $b \* 3`
expr $s + 680
fi
exit

Factorial of given number:


Program:
echo”Enter the value of n:”
read n
i=1
f=1
if [ $n -eq- 0 ]
then
echo”factorial is 1”
else
while [ $i -le $n]
do
f= `expr $f \* $i`
i= `expr $i + 1`
done
fi
echo`factorial value is $f`

Current date and time:


Program:
echo "today's date"
date

Display the Chess board:


Program:
clear
for (( i=1;i<=8;i++ ))
do
for ((j=1;j<=8;j++))
do
if [ `expr $(($i + $j)) % 2` -eq 0 ]
then
echo -e -n "\033[47m "
else
echo -e -n "\033[40m "
fi
done
echo ""
done
echo -e "\033[0m"

8
BASIC MYSQL QUERY PROCESSING
Ex. No: 2

AIM

To implement Data Definition Language (DDL) commands using SQL queries.

DESCRIPTION

Connecting to and Disconnecting from the Server

To connect to the server, you will usually need to provide a MySQL user name
when you invoke mysqland, most likely, a password. If the server runs on a machine other
than the one where you log in, you will also need to specify a host name. Contact your
administrator to find out what connection parameters you should use to connect (that is,
what host, user name, and password to use). Once you know the proper parameters, you
should be able to connect like this:
shell> mysql -h host -u user -p
Enter password: ********
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 25338 to server version: 5.1.54-standard
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>

Create a database
mysql> SHOW DATABASES;
+----------+
| Database |
+----------+
| mysql |
| test |
| tmp |
+----------+

The mysqldatabase describes user access privileges. The test database often is available
as a workspace for users to try things out. The list of databases displayed by the statement
may be different on your machine; SHOW DATABASES does not show databases that
you have no privileges for if you do not have the SHOW DATABASES privilege.
If the test database exists, try to access it:
mysql> USE test

9
Database changed
Creating and Selecting a Database
If the administrator creates your database for you when setting up your permissions, you
can begin using it. Otherwise, you need to create it yourself:

mysql> CREATE DATABASE employee;


mysql> USE employee
Database changed
Creating a Table
mysql> create table employ(id int,fname varchar(20),lname varchar(20),dept
varchar(10),dob date,salary int,experience int);
Query OK, 0 rows affected (0.12 sec)

mysql> describe employ;


+------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| fname | varchar(20) | YES | | NULL | |
| lname | varchar(20) | YES | | NULL | |
| dept | varchar(10) | YES | | NULL | |
| dob | date | YES | | NULL | |
| salary | int(11) | YES | | NULL | |
| experience | int(11) | YES | | NULL | |
+------------+-------------+------+-----+---------+-------+
7 rows in set (0.04 sec)

Inserting data into a Table

mysql> insert into employ values(01,"raja","ram","cse","89-02-08",20000,2);


Query OK, 1 row affected (0.00 sec)

mysql> insert into employ values(02,"deepika",'p',"cse","89-02-08",18600,1);


Query OK, 1 row affected (0.00 sec)

mysql> insert into employ values(02,"praveen",'kumar',"ece","85-06-05",28600,4);


Query OK, 1 row affected (0.00 sec)

mysql> insert into employ values(02,"praveen",'kumar',"eee","82-06-05",48600,9);


Query OK, 1 row affected (0.00 sec)

mysql> insert into employ values(05,"radha",'ravi',"e&i","82-10-10",48600,9);Query OK,


1 row affected (0.00 sec)

Selecting all Records


mysql> select * from employ;

10
+------+---------+-------+------+------------+--------+------------+
| id | fname | lname | dept | dob | salary | experience |
+------+---------+-------+------+------------+--------+------------+
| 1 | raja | ram | cse | 1989-02-08 | 20000 | 2|
| 2 | deepika | p | cse | 1989-02-08 | 18600 | 1|
| 2 | praveen | kumar | ece | 1985-06-05 | 28600 | 4|
| 2 | praveen | kumar | eee | 1982-06-05 | 48600 | 9|
| 5 | radha | ravi | e&i | 1982-10-10 | 48600 | 9|
+------+---------+-------+------+------------+--------+------------+

5 rows in set (0.00 sec)

EXERCISE

Create the tables described below. Each table should contain primary key and not
null attributes.

1. Clientmaster (to store client information): clientno, name, address1, address2,


city, pincode, state and baldue.
2. Productmaster (to store product information): productno, description,
profitpercent, unitmeasure, qtyonhand, reorderlvl, sellprice, costprice.
3. Salesmanmaster(to store salesman working for the company): salesmanno,
salesmanname, address1, address2, city, pincode, state, salamt, tgttoget, ytdsales,
remarks.

11
MYSQL QUERY PROCESSING
Ex. No: 3

AIM
To implement Data Definition Language (DDL) commands using SQL queries.

DESCRIPTION
Selecting a Particular Rows/Columns

mysql> select fname,lname from employ;


+---------+-------+
| fname | lname |
+---------+-------+
| raja | ram |
| deepika | p |
| praveen | kumar |
| praveen | kumar |
| radha | ravi |
+---------+-------+

5 rows in set (0.00 sec)

mysql> select * from employ where dept="cse";


+------+---------+-------+------+------------+--------+------------+
| id | fname | lname | dept | dob | salary | experience |
+------+---------+-------+------+------------+--------+------------+
| 1 | raja | ram | cse | 1989-02-08 | 20000 | 2|
| 2 | deepika | p | cse | 1989-02-08 | 18600 | 1|
+------+---------+-------+------+------------+--------+------------+

2 rows in set (0.00 sec)

mysql> select fname from employ where salary=48600 and experience=9;


+---------+
| fname |
+---------+
| praveen |
| radha |
+---------+

2 rows in set (0.00 sec)

mysql> select * from employ where dept="cse" or experience=1;


+------+---------+-------+------+------------+--------+------------+
| id | fname | lname | dept | dob | salary | experience |
+------+---------+-------+------+------------+--------+------------+

12
| 1 | raja | ram | cse | 1989-02-08 | 20000 | 2|
| 2 | deepika | p | cse | 1989-02-08 | 18600 | 1|
+------+---------+-------+------+------------+--------+------------+
2 rows in set (0.00 sec)

mysql> select distinct dept from employ;


+------+
| dept |
+------+
| cse |
| ece |
| eee |
| e&i |
+------+
4 rows in set (0.00 sec)

mysql> select fname,dob from employ order by dob;


+---------+------------+
| fname | dob |
+---------+------------+
| praveen | 1982-06-05 |
| radha | 1982-10-10 |
| praveen | 1985-06-05 |
| raja | 1989-02-08 |
| deepika | 1989-02-08 |
+---------+------------+
5 rows in set (0.00 sec)

mysql> select fname,dob from employ order by dob desc ;


+---------+------------+
| fname | dob |
+---------+------------+
| raja | 1989-02-08 |
| deepika | 1989-02-08 |
| praveen | 1985-06-05 |
| radha | 1982-10-10 |
| praveen | 1982-06-05 |
+---------+------------+
5 rows in set (0.00 sec)

Age Calculation

mysql> select fname,dob,curdate(),(year(curdate())-year(dob))-


(right(curdate(),5)<right(dob,5)) as age from employ;

+---------+------------+------------+------+
| fname | dob | curdate() | age |
+---------+------------+------------+------+
| raja | 1989-02-08 | 2013-05-02 | 24 |
| deepika | 1989-02-08 | 2013-05-02 | 24 |

13
| praveen | 1985-06-05 | 2013-05-02 | 27 |
| praveen | 1982-06-05 | 2013-05-02 | 30 |
| radha | 1982-10-10 | 2013-05-02 | 30 |
+---------+------------+------------+------+
5 rows in set (0.00 sec)

mysql> select fname,dob,month(dob)from employ;


+---------+------------+------------+
| fname | dob | month(dob) |
+---------+------------+------------+
| raja | 1989-02-08 | 2|
| deepika | 1989-02-08 | 2|
| praveen | 1985-06-05 | 6|
| praveen | 1982-06-05 | 6|
| radha | 1982-10-10 | 10 |
+---------+------------+------------+

5 rows in set (0.00 sec)

Deleting Data

mysql> delete from employ where salary=20000;


Query OK, 1 row affected (0.00 sec)

mysql> select * from employ;


+------+---------+-------+------+------------+--------+------------+
| id | fname | lname | dept | dob | salary | experience |
+------+---------+-------+------+------------+--------+------------+
| 2 | deepika | p | cse | 1989-02-08 | 18600 | 1|
| 2 | praveen | kumar | ece | 1985-06-05 | 28600 | 4|
| 2 | praveen | kumar | eee | 1982-06-05 | 48600 | 9|
| 5 | radha | ravi | e&i | 1982-10-10 | 48600 | 9|
+------+---------+-------+------+------------+--------+------------+
4 rows in set (0.00 sec)

EXERCISE

Create the tables described below and apply various commands, also displays results
for various quires given below. Each table should contain primary key and not null
attributes.

Clientmaster (to store client information): clientno, name, address1, address2, city,
pincode, state and baldue.
Productmaster (to store product information): productno, description, profitpercent,
unitmeasure, qtyonhand, reorderlvl, sellprice, costprice.

14
Salesmanmaster(to store salesman working for the company): salesmanno,
salesmanname, address1, address2, city, pincode, state, salamt, tgttoget, ytdsales,
remarks.

1. a) Find out the names of all the clients.


b) Retrieve the list of names and the cities of all the clients.
c) Change the city of clientno ‘C005’ to ‘Bombay’.
d) Delete all salesmen ffrom the salesmanmaster whose salaries are equal to
Rs.3200.
e) Add a column called ‘telephone’ of data type number to the clientmaster table.
f) Change the name of the salesmanmaster table to s_master.

2. a) Retrieve the entire contents of the clientmaster table.


b) List all the clients who are located in Bombay.
c) Change the cost price of 2GB pendrive to Rs. 400/-
d) Delete from clientmaster where the column state holds the value ‘TamilNadu’.
e) Add a column called ‘mobileno’ of data type number to the salesmantmaster
table.
f) Change the name of the productmaster table to p_master.

3. a) List the various products available from the productmaster table.


b) Find the names of the salesman who have a salary equal to Rs.3000.
c) Change the city of the salesman to salem.
d) Delete all products from productmaster where the quantity on hand is equal
to 120.
e) change the size of sellprice column in productmaster to 10,2.
f) Change the name of the clientmaster table to c_master.

15
PHP PROGRAM TO DISPLAY WELCOME MESSAGE
Ex.No:4

AIM
To write the php program to display the welcome message.

DESCRIPTION

What is PHP?
PHP is the Hypertext Preprocessor.Open-source, server-side scripting language
used to generate dynamic web-pages. PHP scripts reside between reserved PHP tags.This
allows the programmer to embed PHP scripts within HTML pages.
Interpreted language, scripts are parsed at run-time rather than compiled
beforehand. It executed on the server-side. Source-code not visible by client. ‘View
Source’ in browsers does not display the PHP code. Various built-in functions allow for
fast development. Compatible with many popular databases.
PHP was originally developed by the Danish Greenlander Rasmus Lerdorf, and
was subsequently developed as open source. PHP is not a proper web standard - but an
open-source technology. PHP is neither real programming language - but PHP lets you use
so-called scripting in your documents.
To describe what a PHP page is, you could say that it is a file with the extension
.php that contains a combination of HTML tags and scripts that run on a web server.

Running PHP files

 By default Apache is using


/var/www/html default directory
 Type the php file using an editor and save it in
/var/www/html/file.php
 Now you can execute the file by running the browser with
http://localhost/file.php

ALGORITHM
1. Start the program
2. Create a html form to get the user information.
3. Link the form with php page.
4. Php used Post method to receive the data from html page.
5. Execute and Display the output on screen

PROGRAM

sample.html
<html>
<head>PROGRAM FOR WELCOME MESSAGE</head>
<title> SAMPLE PROGRAM</title>
<body>
<br><br>
<form action="welcome.php" method="post">
Name: <input type="text" name="fname"><br><br>

16
Age: <input type="text" name="age"><br><br>
Department:
<select name="dept">
<option value ="cse">cse</option>
<option value ="ece">ece</option>
<option value ="eee">eee</option>
<option value ="e&e">e&i</option>
<option value ="textile">textile</option>
<option value ="nano">nano</option>
</select><br><br>
<input type="submit">
</form>
</body>
</html>

welcome.php

<html>
<head><b>Staff Information</b></head>
<title>WELCOME</title>
<body>
<br><br>
Welcome <?php echo $_POST["fname"]; ?>!<br>
You are <?php echo $_POST["age"]; ?> years old.<br>
You belongs to <?php echo $_POST["dept"]; ?> Department.
</body>
</html>

SAMPLE OUTPUT

Staff Information

Welcome deepika!
You are 24 years old.
You belongs to cse Department.

EXERCISE

1. Write a PHP program to get an Employee details using HTML form and display
them through PHP script.
2. Write a PHP program to get a Student details using HTML form and display them
through PHP script.
3. Write a PHP program to get a Bank Account details of a subscriber using HTML
form and display them through PHP script.

17
SIMPLE DATA STORAGE, OPERATORS AND FUNCTIONS
Ex.No: 5

AIM
To write the php program to implement the simple data storage, operators and
functions.

DESCRIPTION

PHP language supports following type of operators.


 Arithmetic Operators
 Comparision Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators

Operators Categories:
All the operators categorized into following categories:

 Unary prefix operators, which precede a single operand.


 Binary operators, which take two operands and perform a variety of arithmetic and
logical operations.
 The conditional operator (a ternary operator), which takes three operands and
evaluates either the second or third expression, depending on the evaluation of the
first expression.
 Assignment operators, which assign a value to a variable.

Precedence of PHP Operators:


Operator precedence determines the grouping of terms in an expression. This
affects how an expression is evaluated. Certain operators have higher precedence than
others; for example, the multiplication operator has higher precedence than the addition
operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has
higher precedence than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those
with the lowest appear at the bottom. Within an expression, higher precedence operators
will be evaluated first.
Create a PHP Function
A function will be executed by a call to the function.
Syntax
function functionName()
{ code to be executed;
}

ALGORITHM
1. Start the program.
2. Create an html form to get the value of 2 numbers.

18
3. Select the operation from drop down list.
4. Write a code to perform arithmetic operation using functions.
5. Execute the code.
6. Display the result.

PROGRAM

Main.html
<html>
<body>
<marquee><b>Program using operator and function<b></marquee>
<form action ="operation.php" method ="post">
<b>Enter the number to perform operation</b><br>
<br>
Number1: <input type="text" name="num1"><br><br>
Number2: <input type="text" name="num2"><br><br>
<select name="option">
<option value ="add">addition</option>
<option value ="sub">subtraction</option>
<option value ="mul">Multiplication</option>
<option value ="div">Division</option>
</select><br><br>
<input type="submit" name="submit"><br><br>
</form>
</body>
</html>

Operation.php

<html>
<body>
<?php
switch($_POST['option'])
{
case "add":
add();
break;
case "sub":
sub();
break;
case "mul":
mul();
break;
case "div":
div();
break;
default:
echo"no";
}
function add()

19
{
$sum=$_POST["num1"]+$_POST["num2"];
echo "sum of 2 numbers is $sum";
}
function sub()
{
$sub=$_POST["num1"]-$_POST["num2"];
echo "subtraction of 2 numbers is $sub";
}
function mul()
{
$mul=$_POST["num1"]*$_POST["num2"];
echo "Multiplication of 2 numbers is $mul";
}
function div()
{
$div=$_POST["num1"]/$_POST["num2"];
echo "Division value is $div";
}
?>
<br><br>
<a href="main.html">Go to Main Page</a>
</body></html>

SAMPLE INPUT & OUTPUT:

Enter the number to perform operation

Number1: 20

Number2: 30

addition

SUBMIT

sum of 2 numbers is 50

Go to Main Page

20
EXERCISE

1. Write a PHP program for calculating the least of four numbers , maximum of two
numbers , n th root of a number, LCM of three numbers and GCD of three numbers,
checking whether a number is Amstrong number, and prime number or composite
number by getting appropriate inputs though keyboard and print the results using
functions.
2. Write a PHP program for finding the greatest of two numbers , the smallest of three
numbers , average of four numbers , power of n , cube root , square root of a number
and reciprocal of a number by getting appropriate inputs through keyboard and print
the results using functions.

21
STRING HANDLING FUNCTIONS
Ex.No: 6

AIM
To write a PHP program to implement the string handling functions.

DESCRIPTION

PHP has a vast selection of built-in string handling functions that allow you to
easily manipulate strings in almost any possible way. However, learning all these
functions, remembering what they do, and when they might come in handy can be a bit
daunting, especially for new developers. There is no way I can cover every string function
in one article, and besides, that is what the PHP manual is for! But what I will do is show
how to work with some of the most commonly used string handling functions that you
should know. After this, you’ll be working with strings as well as any concert violinist.
PHP offers several functions that enable you to manipulate the case of characters
within a string without having to edit the string character by character. Why would you
care about this? Well maybe you want to ensure that certain text is all in upper case such
as acronyms, titles, for emphasis or just to ensure names are capitalized correctly. Or
maybe you just want to compare two strings and you want to ensure the letters you are
comparing are the same character set. The case manipulation functions are pretty easy to
get to grips with; you just pass the string as a parameter to the function and the return
value you is the processed string.

A Quick Trim
Sometimes a string needs trimming round the edges. It may have whitespace or
other characters at the beginning or end which needs removing. The whitespace can be an
actual space character, but it can also be a tab, carriage return, etc. One example of when
you might need to do something like this is when you’re working with user input and you
want to clean it up it before you start processing it. The trim() function in PHP lets you to
do just that; you can pass the string as a parameter and all whitespace from the beginning
and end of that string will be removed.
Cutting Strings Down to Size
Another common situation is finding specific text within a given string and
“cutting it” out so you can do something else with it. To cut a string down to size, you
need a good pair of scissors, and in PHP your scissors are the substr() function.
Finally, let’s look at replacing a piece of the string with something else, for which
you can use str_replace() function.

ALGORITHM
1. Start the program.
2. Create an html form to get the String.
3. Select the operation from radio button list.
4. Write a code to perform string conversion using string handling functions.
5. Execute the code.
6. Display the result.

22
PROGRAM

Main.html

<html>
<head>
</head>
<title> string handling</title>
<body>
<marquee><b>STRING HANDLING </b></marquee>
<br>
<br>
<br>
<br>
<form action="string.php" method="post">
<b> Enter the text:</b> <input type="text" name="text">
<br>
<br>
<b>Select the Option</b><br><br>
<input type="radio" name="option" value="1"> Convert To UpperCase</input><br>
<input type="radio" name="option" value="2"> Convert To LowerCase</input><br>
<input type="radio" name="option" value="3"> Find the String Length</input>
<br>
<input type="radio" name="option" value="4"> Perform String Reverse</input>
<br>
</b>
<br>
<br>
<input type="submit" value="submit">
</form>
</body>
</html>

String.php

<html>
<body>
<?php
switch($_POST['option'])
{
case 1:
$strg=strtoupper($_POST['text']);
echo "Converted text is $strg";
break;
case 2:
$strg=strtolower($_POST['text']);
echo "Converted text is $strg";
break;

23
case 3:
$strg=strlen($_POST['text']);
echo "Length of given text is $strg";
break;
case 4:
$strg=strrev($_POST['text']);
echo "Reversed text is $strg ";
break;
default:
echo"Select any one option";
}
?>
<br>
<br>
<a href="main.html">Go to Main Page</a>
</body>
</html>

SAMPLE INPUT & OUTPUT


Enter the text:

Select the Option

Convert To UpperCase
Convert To LowerCase
Find the String Length
Perform String Reverse

submit

Converted text is DEEPIKA

Go to Main Page

EXERCISE

1. Write a PHP program to get a paragraph for converting it into upper case and
Sentence case using String handling functions and HTML form
2. Write a PHP program to get a paragraph for converting it into lower case and
Title case using String handling functions and HTML form

24
COMPARISON OF STRINGS
Ex.No: 7

AIM
To write a PHP program PHP program to compare the strings "apple", "orange",
"banana" between them and displays the comparison result..

DESCRIPTION

Compare strings
Compares the value of the string object (or a substring) to the sequence of
characters specified by its arguments.The compared string is the value of the string object
or -if the signature used has a pos and a len parameters- the substring that begins at its
character in position pos and spans len characters.

Two types of string comparison.


 Case sensitive string comparison
 Case insensitive string comparison
Case insensitive string comparison
Two strings are compare without considering their case by using strcasecmp
function. This function takes two string inputs and returns 0 if both the strings are equal (
or matching ), returns < 0 if fist string is less than second string and returns > 0 of fist
string is greater than second string. For case sensitive string matching use strcmp function.

Here is a sample code using strcasecomp function to check two strings.


$str1="Hello World";
$str2="hello world";
echo strcasecmp($str1,$str2);
if(strcasecmp($str1,$str2)==0){
echo "Both strings are matching";
}else{
echo "Both strings are different ";
}

Case sensitive string comparison


Case sensitive string comparision can be done by using strcmp function in PHP.
This function returns < 0 if first string is less than second string, returns > 0 if first string is
greater than second string and returns 0 if both the strings are equal.For a case in sensitive
string comparison use strcasecmp function.

Here is a sample code using strcomp function to check two strings.


$str1="Hello World";
$str2="hello world";
echo strcmp($str1,$str2);
if(strcmp($str1,$str2)==0){
echo "Both strings are matching";
}else{

25
echo "Both strings are different ";
}

ALGORITHM
1. Start the program.
2. Create an html form to get the 2 Strings to compare.
3. Write a code to perform string comparison.
4. Execute the code.
5. Display the result.

PROGRAM
main.html

<html>
<head> <b>String Comparison</b></head>
<title>String Comparison</title>
<body>
<br>
<br>
<form action="string.php" method="post">
<b><i>Enter the Strings to compare</i></b>
<br>
<br>
String1 : <input type="text" name="str1">
<br>
String2 : <input type="text" name="str2">
<br>
<br>
<input type="submit" name="Submit">
</form>
</body>
</html>

string.php

<html>
<body>
<?php
$string1=$_POST['str1'];
$string2=$_POST['str2'];
$result=strcmp($string1,$string2);
if ($result > 0)
{
echo $string1." is greater than ".$string2;
}
else if ($result < 0)
{
echo $string2." is greater than ".$string1;
}
else

26
{
echo $string1." and ".$string2." are equal";
}
?>
<br>
<br>
<br>
<a href="main.html">Go to Main Page</a>
</body>
</html>

SAMPLE INPUT & OUTPUT

String Comparison
Enter the Strings to compare

String1 :
String2 :

SUBMIT

deepika is greater than deepi

Go to Main Page

EXERCISE

1. Write a PHP program to get a paragraph and a word for determining the no of
occurrences of the word in the paragraph and number of words in the paragraph
using String handling functions and HTML form

2. Write a PHP program to get n number of names and sort them in ascending order
and descending order using String handling functions and HTML form

27
PROGRAM FOR A SIMPLE DATABASE CONNECTION USING PHP
Ex.No: 8

AIM

To write a program for implementing a simple database connectivity using PHP.

DESCRIPTION
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:3306"
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);
?>

28
CODING
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost,
$dbuser, $dbpass) or die ('Error
connecting to mysql');

$dbname = 'employee';
mysql_select_db($dbname);
mysql_close($conn);
?>
SAMPLE OUTPUT

EXERCISES

1. Write a PHP script to create a table Employee in MySQL Database and insert the
record (Empno,Ename,Basicpay) into the database through HTML form

2. Write a PHP script to delete a particular record and display all the records in the
Employee Table through HTML form

3. Write a PHP script to update a particular record and display all the records in the
Employee Table through HTML form

29
IMPLEMENTATION OF FILE HANDLING OPERATIONS
Ex.No: 9

AIM
To write a php program to implement the file handling operations

DESCRIPTION

ALGORITHM:

1 Start the program.


2.Create text file to perform operation
3.Write a html script to get the message
4.Write a php script to write the given message into file
5. Display the result.
6. Stop the program.

PROGRAM

main.html

<html>
<head>File Handling</head>
<title>File Handling</title>
<body>
<form action="file.php" method="post">
<b>Enter the message</b>
<br>
<br>
<input type="text" name="message">
<input type="submit" value="submit">
</form>
</body>
</html>

file.php
<?php
$save = $_POST['message'];
$path = "/var/www/html/file";
$filename = "file";
while (file_exists($path.$filename))
{
$fnum++;
$filename = "file".$fnum;
echo "copied"
}
$handle = fopen($path.$filename, "w");

30
fwrite($handle,$save);
fclose($handle);
?>

SAMPLE INPUT & OUTPUT

File Handling
Enter the message

submit

Copied

EXERCISE
1. Write a PHP script to create a file for writing data by getting it through HTML
form and print it on console
2. Write a PHP script to create a file for appending data by getting it through HTML
form and print it on console

31
SQL QUERIES VIA PHP
Ex.No: 10

AIM
To write a program to make simple SQL queries via PHP.

DESCRIPTION

MySQL works very well in combination of various programming languages like PERL,
C, C++, JAVA and PHP. Out of these languages, PHP is the most popular one because of
its web application development capabilities.
PHP provides various functions to
access MySQL database and to
manipulate data records inside MySQL
database. You would require to call PHP
functions in the same way you call any
other PHP function.
The PHP functions for use with MySQL
have the following general format:
mysql_function(value,value,...);
The second part of the function name is
specific to the function, usually a word
that describes what the function does.
mysqli_connect($connect);
mysqli_query($connect,"SQL statement");
Following example shows a generic
sysntax of PHP to call any MySQL
function.
<html>
<head>
<title>PHP with MySQL</title>
</head>
<body>
<?php
$retval = mysql_function(value, [value,...]);
if( !$retval )
{
die ( "Error: a related error message" );
}
// Otherwise MySQL or PHP Statements
?>
</body>
</html>

32
Creation of MySQL Database
Creation of Database using mysqladmin:
You would need special privilege to
create or to delete a MySQL database.
So assuming you have access to root
user, you can create any database using
mysql mysqladmin binary.
Example:
Here is a simple example to create
database called TUTOR:
root@host]# mysqladmin -u root -p create TUTOR
Enter password:******
This will create a MySQL database
TUTOR.

SQL SELECT command


The SQL SELECT command is used to
fetch data from MySQL database. You
can use this command at mysql> prompt
as well as in any script like PHP.
Syntax:
Here is generic SQL syntax of SELECT
command to fetch data from MySQL
table:
SELECT field1, field2,...fieldN table_name1, table_name2...
[WHERE Clause][OFFSET M ][LIMIT N]
1. You can use one or more tables
separated by comma to include
various condition using a WHERE
clause. But WHERE clause is an
optional part of SELECT command.
2. You can fetch one or more fields in
a single SELECT command.
3. You can specify star (*) in place of
fields. In this case SELECT will
return all the fields
4. You can specify any condition using
WHERE clause.
5. You can specify an offset using
OFFSET from where SELECT will
start returning records. By default
offset is zero
6. You can limit the number of
returned using LIMIT attribute.
Fetching Data from Command Prompt:
This will use SQL SELECT command to
fetch data from MySQL table
tutorials_tbl

33
Example:
Following example will return all the
records from tutor_tbl table:
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTOR;
Database changed
mysql> SELECT * from tutor_tbl
+-------------+----------------+-----------------+-----------------+
| tutor_id | tutor_title | tutor_author | submission_date |
+-------------+----------------+-----------------+-----------------+
| 1 | Learn PHP | John Poul | 2007-05-21 |
| 2 | Learn MySQL | Abdul S | 2007-05-21 |
| 3 | JAVA Tutorial | Sanjay | 2007-05-21 |
+-------------+----------------+-----------------+-----------------+
3 rows in set (0.01 sec)
mysql>
Insert data into MySQL
To insert data into MySQL table you
would need to use SQL INSERT INTO
command. You can insert data into
MySQL table by using mysql> prompt
or by using any script like PHP.
Syntax:
Here is generic SQL syntax of INSERT
INTO command to insert data into
MySQL table:
INSERT INTO table_name ( field1, field2,...fieldN )VALUES (value1,
value2,...valueN );
To insert string data types it is required
to keep all the values into double or
single quote, for example:- "value".
Inserting Data from Command Prompt:
This will use SQL INSERT INTO
command to insert data into MySQL
table tutor_tbl
Example:
Following example will create 3 records
into tutor_tbl table:
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTOR;
Database changed
mysql> INSERT INTO tutor_tbl
->(tutor_title, tutor_author, submission_date)
->VALUES
->("Learn PHP", "John Poul", NOW());
Query OK, 1 row affected (0.01 sec)
mysql> INSERT INTO tutorials_tbl
->(tutorial_title, tutorial_author, submission_date)

34
->VALUES
->("Learn MySQL", "Abdul S", NOW());
Query OK, 1 row affected (0.01 sec)
mysql> INSERT INTO tutorials_tbl
->(tutorial_title, tutorial_author, submission_date)
->VALUES ->("JAVA Tutorial", "Sanjay", '2007-05-06');
Query OK, 1 row affected (0.01 sec)
mysql>
NOTE: Please note that all the arrow
signs (->) are not part of SQL command
they are indicating a new line and they
are created automatically by MySQL
prompt while pressing enter key without
giving a semi colon at the end of each
line of the command.
In the above example we have not
provided tutorial_id because at the time
of table create we had given
AUTO_INCREMENT option for this
field. So MySQL takes care of inserting
these IDs automatically. Here N
MySQL UPDATE Query
There may be a requirement where
existing data in a MySQL table need to
be modified. You can do so by using
SQL UPDATE command. This will
modify any field value of any MySQL
table.
Syntax:
Here is generic SQL syntax of UPDATE
command to modify data into MySQL
table:
UPDATE table_name SET field1=new-value1, field2=new-value2
[WHERE Clause]
1. You can update one or more field
all together.
2. You can specify any condition
using WHERE clause.
3. You can update values in a single
table at a time.
The WHERE clause is very useful when
you want to update selected rows in a
table.
Updating Data from Command Prompt:
This will use SQL UPDATE command
with WHERE clause to update selected
data into MySQL table tutorials_tbl

35
Example:
Following example will update
tutor_title field for a record having
tutor_id as 3.
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTOR;
Database changed
mysql> UPDATE tutor_tbl
-> SET tutorial_title='Learning JAVA'
-> WHERE tutorial_id=3;
Query OK, 1 row affected (0.04 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql>
Deleting Data from Command Prompt:
This will use SQL DELETE command
with WHERE clause to delete selected
data into MySQL table tutor_tbl
Example:
Following example will delete a record
into tutor_tbl whose tutor_id is 3.
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTOR;
Database changed
mysql> DELETE FROM tutor_tbl WHERE tutor_id=3;
Query OK, 1 row affected (0.23 sec)
mysql>

CODING
Connecting to MySQL Server using PHP Script:
Try out following example to connect to MySQL server

<html>
<head>
<title>Connecting MySQL Server</title>
</head>
<body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($conn);
?>

36
</body>
</html>

Create Database using PHP Script:


PHP uses mysql_query function to
create or delete a MySQL database. This
function takes two parameters and
returns TRUE on success or FALSE on
failure.
Syntax:
bool mysql_query( sql, connection );

Parameter Description
sql Required - SQL query to create or delete a MySQL database
connection Optional - if not specified then last opened connection by
mysql_connect will be used.

Try out following example to create a


database:
<html>
<head>
<title>Creating MySQL Database</title>
</head>
<body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = 'CREATE DATABASE TUTOR';
$retval = mysql_query($sql, $conn );
if(! $retval )
{
die('Could not create database: ' . mysql_error());
}
echo "Database TUTOR created successfully\n";
mysql_close($conn);
?>
</body>
</html>

37
Fetching Data Using PHP Script:
You can use same SQL SELECT
command into PHP function
mysql_query(). This function is used to
execute SQL command and later another
PHP function mysql_fetch_array() can
be used to fetch all the selected data.
This function returns row as an
associative array, a numeric array, or
both. This function returns FALSE if
there are no more rows.
Below is a simple example to fetch
records from tutor_tbl table.
Try out following example to display all
the records from tutor_tbl table.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT tutor_id, tutor_title,
tutor_author, submission_date
FROM tutor_tbl';

mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "Tutorial ID :{$row['tutor_id']} <br> ".
"Title: {$row['tutor_title']} <br> ".
"Author: {$row['tutor_author']} <br> ".
"Submission Date : {$row['submission_date']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>

Deleting Data Using PHP Script:


You can use SQL DELETE command
with or without WHERE CLAUSE into
PHP function mysql_query(). This

38
function will execute SQL command in
similar way it is executed at mysql>
prompt.
Example:
Try out following example to delete a
record into tutor_tbl whose tutor_id is 3.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'DELETE FROM tutorials_tbl
WHERE tutorial_id=3';

mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not delete data: ' . mysql_error());
}
echo "Deleted data successfully\n";
mysql_close($conn);
?>

SAMPLE OUTPUT

Connected successfully

Database TUTOR created successfully

Tutor ID :1
Title: Learn PHP
Author: | John Poul
Submission Date : 2007-05-21

Tutor ID :2
Title: Learn MySQL
Author: | Abdul S
Submission Date : 2007-05-21

Tutor ID :3
Title: | JAVA Tutorial
Author: Sanjay
Submission Date : 2007-05-21

39
Deleted data successfully

EXERCISE

1. Write a PHP program for updating data in Employee table and print a report in the
form of Empno, Ename, Basicpay, DA, HRA MA, TA, Gsal, Epf, Netsal and grand
total for all records through HTML form with all validations

2. Write a PHP program for updating data in Student table and print a report in the
form of Rollno, Sname, 5 subjects marks result, class, average through HTML
form with all validations

40

You might also like