Open Source Lab Manual
Open Source Lab Manual
Ex.No: 1a
AIM
To execute various basic LINUX commands..
DESCRIPTION
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.
Simple Commands:
CAT Commands:
Delete Commands:
List Commands:
2
$ls-l: To list the filenames pagewise
Move Commands:
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.
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 –no filename: display the number of lines from the file
$ tail +no filename: display from the nth line
Link commands:
4
5
SIMPLE SHELL PROGRAMMING
Ex.No: 1b
AIM
To write the shell programming using the command syntax, simple functions and
basic tests.
DESCRIPTION
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
8
BASIC MYSQL QUERY PROCESSING
Ex. No: 2
AIM
DESCRIPTION
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:
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|
+------+---------+-------+------+------------+--------+------------+
EXERCISE
Create the tables described below. Each table should contain primary key and not
null attributes.
11
MYSQL QUERY PROCESSING
Ex. No: 3
AIM
To implement Data Definition Language (DDL) commands using SQL queries.
DESCRIPTION
Selecting a Particular Rows/Columns
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)
Age Calculation
+---------+------------+------------+------+
| 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)
Deleting Data
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.
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.
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
Operators Categories:
All the operators categorized into following categories:
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>
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>
Convert To UpperCase
Convert To LowerCase
Find the String Length
Perform String Reverse
submit
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.
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>
String Comparison
Enter the Strings to compare
String1 :
String2 :
SUBMIT
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
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:
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);
?>
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.
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>
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.
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);
?>
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
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