Ost Lab Manual r15

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 53

OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

Experiment 01:
a) Performing basic DML, DDL commands using MySQL
Employee table

Dept table

Queries
List employee details.
SQL> select * from emp2b4;

List the department Details.


SQL> select * from dept2b4;

Update emp2b4 table and change employee name, ADAMS to ADAM.


SQL> update emp2b4 set ename='ADAM' where empno=7876;

Update emp2b4 table and change sal,comm. to 2000 & 500 respectively for an
employee with empno 7844.
SQL> update emp2b4 set sal=2000, comm=500 where empno=7844;

Prepared by : G SRIKANTH REDDY Page 1


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

Select deptno, dname ,of deptno>10 and located in ‘NEWYORK’.


SQL> select deptno,dname from dept2b4 where deptno>10 and loc='NEW YORK';

List all employee details whose empno=10 and whose job is clerk.
SQL> select * from emp2b4 where deptno=10 and job='CLERK';

List all employee hired during 1981?


SQL> select * from emp2b4 where hiredate between '01-JAN-1981' and '31-DEC-1981';

List all empno, ename of all employee in format “empno ename”.


SQL> select empno,ename from emp2b4;

Find the total number of clerks in department 10.


SQL> select count(*),deptno from emp2b4 where job='CLERK' group by deptno having
deptno=10;

Find the average salary of employees


SQL> select avg(sal) from emp2b4;

Find minimum salary paid employee and employee details with that salaries.
SQL> select * from emp2b4 where sal=(select min(sal) from emp2b4);

Find the name of employee which starts with ‘A’ and end with ‘N’
SQL> select e.ename from emp2b4 e where e.ename like 'A%N';

List all employees who have a salary greater than 1500 in the order of department
number.
SQL> select * from emp2b4 where sal>1500 order by deptno;

List deptno , dname ,min(sal) for all departments.


SQL> select d.deptno,d.dname,min(e.sal) from dept2b4 d,emp2b4 e where
d.deptno=e.deptno group by d.deptno,d.dname;

List all employees deptno.-wise.


SQL> select ename,deptno from emp2b4 order by deptno;

Display all employee names, number, deptname & location of all employees.
SQL> select e.ename,e.empno,d.dname,d.loc from emp2b4 e,dept2b4 d where
d.deptno=e.deptno;

Find the employees belongs to the research department.


SQL> select * from emp2b4 e where e.deptno=(select d.deptno from dept2b4 d where
d.dname='RESEARCH');

Prepared by : G SRIKANTH REDDY Page 2


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

Find employee name employee number, their salary who were hired after 01/02/97.
SQL> select ename,empno,sal from emp2b4 where hiredate>'01-FEB-1997';

Find the second maximum salary of employee table.


SQL> select max(sal) from emp2b4 where sal<(select max(sal) from emp2b4);

Find employee name from employee table whose manager is NULL.


SQL> select ename from emp2b4 where mgr is null;

b) STUDENT PROGRESS MONITORING SYSTEM: A database is to be designed for a


college to monitor students progress throughout their course of study. The
students are reading for a degree (such as BA, BA (Hons) MSc, etc) within the
framework of the modular system. The college provides a number of modules,
each being characterized by its code, title, and credit value, module leader,
teaching staff and the department they come from. A module is co-ordinated by
a module leader who shares teaching duties with one or more lecturers. A
lecturer may teach (and be a module leader for) more than one module. Students
are free to choose any module they wish but the following rules must be
observed: some modules require prerequisites modules and some degree
programmes have compulsory modules. The database is also to contain some
information about students including their numbers, names, addresses, degrees
they read for, and their past performance (i.e. modules taken and examination
results). The college will provide the data given below
 College code
 College Name
 College Location
 Seat Distribution
Answer to the following Queries:
i. Comprehend the data given in the case study by creating respective tables
with primary keys and foreign keys wherever required.
ii. Insert values into the tables created (Be vigilant about Master- Slave tables).
iii. Display the Students who have taken M.Sc course.
iv. Display the Module code and Number of Modules taught by each Lecturer.
v. Retrieve the Lecturer names who are not Module Leaders.
vi. Display the Department name which offers ‘English’ module.
vii. Retrieve the Prerequisite Courses offered by every Department (with
Department names).
viii. Present the Lecturer ID and Name who teaches ‘Mathematics’.
ix. Discover the number of years a Module is taught.
x. List out all the Faculties who work for ‘Statistics’ Department

Experiment 02:
EMPLOYEE AND DEPARTMENT DATABASE

Prepared by : G SRIKANTH REDDY Page 3


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

The BlueX Company Pvt. Ltd. has maintaining Employee information contains employee
details. The company has four departments. Any employee working in the company
belongs to any one of the department. An employee joined in company above 25 years
only. The company may give commission for every employee if and only if more than 2
years experience. Construct the database design with that there is no redundancy.
Answer to the following Queries:
i. List Employee Details.
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
17-Dec-
7369 SMITH CLERK 7902 80 800 20
20-Feb-
7499 ALLEN SALESMAN 7698 81 1600 300 30
22-Feb-
7521 WARD SALESMAN 7698 81 1250 500 30
02-Apr-
7566 JONES MANAGER 7839 81 2975 20
28-Sep-
7654 MARTIN SALESMAN 7698 81 1250 1400 30
7782 CLARK MANAGER 7839 09-Jun-81 2450 10
09-Dec-
7788 SCOTT ANALYST 7566 82 3000 20
17-Nov-
7839 KING PRESIDENT 81 5000 10
08-Sep-
7844 TURNER SALESMAN 7698 81 1500 0 30
7876 ADAMS CLERK 7788 12-Jan-83 1100 20
03-Dec-
7902 FORD ANALYST 7566 81 3000 20
7934 MILLER CLERK 7782 23-Jan-82 1300 10

ii. List the department Details.


DEPTNO DNAME LOC
---------- --------------
-------------
NEW
10 ACCOUNTING YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

iii. Update emp table and change employee name, ADAMS to ADAM.
update emp set ename='ADAM' where empno=7876;

iv. Update emp table and change sal, comm. To 2000 &500 to an employee no
7844.
update emp set sal=2000, comm=500 where empno=7844;

v. Select deptno, dname ,of deptno>10 and located in ‘NEWYORK’.

Prepared by : G SRIKANTH REDDY Page 4


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

select deptno,dname from dept where deptno>10 and loc='NEW YORK';

vi. List all employee details who belongs to deptno=10 and whose job is clerk.
select * from emp where deptno=10 and job='CLERK';

vii. Find the total number of clerks in department 10?


select count(*),deptno from emp where job='CLERK' group by deptno having deptno=10;

viii. Find the average salary of employees?


select avg(sal) from emp;

ix. List all employees who have a salary greater than 1500 in the order of
department number.
select * from emp where sal>1500 order by deptno;

x. Find minimum salary paid employee and employee details with that salaries?
select * from emp where sal=(select min(sal) from emp);

xi. Find the name of employee which starts with ‘A’ and end with ‘N’?
select e.ename from emp e where e.ename like 'A%N';

xii. List all employees who have a salary greater than 15000 in the order of
department number?
select * from emp where sal>1500 order by deptno;

xiii. List deptno , dname ,min(sal) for all departments?


select d.deptno,d.dname,min(e.sal) from dept d,emp e where d.deptno=e.deptno group
by d.deptno,d.dname;

xiv. Display all employee names, number, deptname & location of all employees?
select e.ename,e.empno,d.dname,d.loc from emp e,dept d where d.deptno=e.deptno;

xv. Find employee name employee number, their salary who were hired after
01/02/97
select ename,empno,sal from emp where hiredate>'01-FEB-1997';

PHP:
Experiment 03:
a) Write a PHP program to validate form contents using regular expressions.
Processing page
<?php

Prepared by : G SRIKANTH REDDY Page 5


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

if($_POST)
{
$name = $_POST['name'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$gender = $_POST['gender'];
// Full Name
if (eregi('^[A-Za-z0-9 ]{3,20}$',$name))
{
$valid_name=$name;
}
else
{
$error_name='Enter valid Name.';
}

// Email
if (eregi('^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$', $email))
{
$valid_email=$email;
}
else
{
$error_email='Enter valid Email.';
}

// Usename min 2 char max 20 char


if (eregi('^[A-Za-z0-9_]{3,20}$',$username))
{
$valid_username=$username;
}
else
{
$error_username='Enter valid Username min 3 Chars.';
}

// Password min 6 char max 20 char


if (eregi('^[A-Za-z0-9!@#$%^&*()_]{6,20}$',$password))
{
$valid_password=$password;
}
else
{
$error_password='Enter valid Password min 6 Chars.';

Prepared by : G SRIKANTH REDDY Page 6


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

// Gender
if ($gender==0)
{
$error_gender='Select Gender';
}
else
{
$valid_gender=$gender;
}

if((strlen($valid_name)>0)&&(strlen($valid_email)>0)
&&(strlen($valid_username)>0)&&(strlen($valid_password)>0) && $valid_gender>0 )
{
mysql_query(" SQL insert statement ");
header("Location: thanks.html");
}
else{ }

}
?>
Front page
<php include("validation.php"); ?>
<form method="post" action="" name="form">
Full name : <input type="text" name="name" value="<?php echo $valid_name; ?>" />
<?php echo $error_name; ?>
Email : <input type="text" name="name" value="<?php echo $valid_email; ?>" />
<?php echo $error_email; ?>
Username : <input type="text" name="name" value="<?php echo $valid_username; ?>"
/>
<?php echo $error_username; ?>
Password : <input type="password" name="name" value="<?php echo $valid_password;
?>" />
<?php echo $error_password; ?>
Gender : <select name="gender">
<option value="0">Gender</option>
<option value="1">Male</option>
<option value="2">Female</option>
</select>
<?php echo $error_gender; ?>
</form>

Experiment 03:

Prepared by : G SRIKANTH REDDY Page 7


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

b) Write a PHP program to merge the contents of two files and store into another
file.
$lines = file('Country.txt');
$lines2 = file('countryenglish.txt');

foreach ($lines as $key => $val) {


$lines[$key] = $val.$lines2[$key];
}

file_put_contents('countryenglish2.txt', implode("\n", $lines));

Experiment 04:
a) Write a PHP program to create a ZIP file using PHP.
/* creates a compressed zip file */
function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE :
ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of

Prepared by : G SRIKANTH REDDY Page 8


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

',$zip->status;

//close the zip -- done!


$zip->close();

//check to make sure the file exists


return file_exists($destination);
}
else
{
return false;
}
}

Experiment 04:
b) Write a PHP program to validate IP address, Integer and E-mail using filters.
IP address
<?php
$ip = "127.0.0.1";

if (!filter_var($ip, FILTER_VALIDATE_IP) === false) {


echo("$ip is a valid IP address");
} else {
echo("$ip is not a valid IP address");
}
?>
Email address
<?php
$email = "john.doe@example.com";

// Remove all illegal characters from email


$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate e-mail
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
?>
Integer
<?php
$int = 100;

Prepared by : G SRIKANTH REDDY Page 9


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

if (!filter_var($int, FILTER_VALIDATE_INT) === false) {


echo("Integer is valid");
} else {
echo("Integer is not valid");
}
?>

Experiment 05:
a) Write a PHP program to retrieve the data from MySQL database
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

Prepared by : G SRIKANTH REDDY Page 10


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

$sql = "SELECT id, firstname, lastname FROM MyGuests";


$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"].
"<br>";
}
} else {
echo "0 results";
}

mysqli_close($conn);
?>

Experiment 05:
b) Write a PHP program to implement sessions and cookies.
Creating a cookie

<?php
setcookie("user_name", "Guru99", time()+ 60,'/'); // expires after 60 seconds
echo 'the cookie has been set for 60 seconds';
?>
Retrieving a cookie

<?php
print_r($_COOKIE); //output the contents of the cookie array variable
?>
Deleting a cookie

<?php
setcookie("user_name", "Guru99", time() - 360,'/');
?>
Creating and accessing a session
<?php

session_start(); //start the PHP_session function

if(isset($_SESSION['page_count']))
{
$_SESSION['page_count'] += 1;
}

Prepared by : G SRIKANTH REDDY Page 11


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

else
{
$_SESSION['page_count'] = 1;
}
echo 'You are visitor number ' . $_SESSION['page_count'];

?>
Destroying a session
<?php
session_destroy(); //destroy entire session
?>

Experiment 06:
a) Write a PHP program to authenticate login credentials.
HTML page
<form name="frmUser" method="post" action="">
<div class="message"><?php if($message!="") { echo $message; } ?></div>
<table border="0" cellpadding="10" cellspacing="1" width="500"
align="center" class="tblLogin">
<tr class="tableheader">
<td align="center" colspan="2">Enter Login Details</td>
</tr>
<tr class="tablerow">
<td>
<input type="text" name="userName" placeholder="User Name"
class="login-input"></td>
</tr>
<tr class="tablerow">
<td>
<input type="password" name="password"
placeholder="Password" class="login-input"></td>
</tr>
<tr class="tableheader">
<td align="center" colspan="2"><input type="submit"
name="submit" value="Submit" class="btnSubmit"></td>
</tr>
</table>
</form>
PHP program
<?php

Prepared by : G SRIKANTH REDDY Page 12


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

$message="";
if(count($_POST)>0) {
$conn = mysqli_connect("localhost","root","","phppot_examples");
$result = mysqli_query($conn,"SELECT * FROM users WHERE user_name='" .
$_POST["userName"] . "' and password = '". $_POST["password"]."'");
$count = mysqli_num_rows($result);
if($count==0) {
$message = "Invalid Username or Password!";
} else {
$message = "You are successfully authenticated!";
}
}
?

Experiment 06:
b) Write a PHP program to insert the contents of student registration form (Rno,
name, branch, age, email, and phone) into MySQL database.

HTML Page for registration

<html>
<body>
<form action="2a.php" method="post">
NA:<input type="text" name="name"/></br>
S1:<input type="text" name="rno"/></br>
S2:<input type="text" name="branch"/></br>
S3:<input type="text" name="age"/></br>
S4:<input type="text" name="email"/></br>
S5:<input type="text" name="phone"/></br>

</br>
<input type="submit"/>
</form>
</body>
</html>

Inserting values into database


<?php

session_start();

$servername = "localhost";
$username = "root";
$password = "root";

Prepared by : G SRIKANTH REDDY Page 13


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

$dbname = "mahi";

if(isset($_SESSION['val'])) {
$_SESSION["val"] = $_SESSION["val"]+1;
}
else
$_SESSION["val"] = 1;

echo($_SESSION["val"]);

$conn = mysqli_connect($servername, $username, $password, $dbname);

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$total=0;
$name=$_POST["name"];
$s1=$_POST["rno"];
$s2=$_POST["age"];
$s3=$_POST["branch"];
$s4=$_POST["email"];
$s5=$_POST["phone"];

$sql = "INSERT INTO students VALUES ('$name',’$s1’,’$s2’,’$s3’,’$s4’,’$s5’)";

mysqli_query($conn, $sql);

if ($_SESSION["val"]>=6) {
session_destroy();
header("Location: red.php");

}
else
{
header("Location: 2lab.html");
}

mysqli_close($conn);
?>

Experiment 06:

Prepared by : G SRIKANTH REDDY Page 14


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

c) Write an AJAX script to perform search operation on MySQL database.


Get the table ready
CREATE TABLE countries (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL
);
Creating the Search Form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP Live MySQL Database Search</title>
<style type="text/css">
body{
font-family: Arail, sans-serif;
}
/* Formatting search box */
.search-box{
width: 300px;
position: relative;
display: inline-block;
font-size: 14px;
}
.search-box input[type="text"]{
height: 32px;
padding: 5px 10px;
border: 1px solid #CCCCCC;
font-size: 14px;
}
.result{
position: absolute;
z-index: 999;
top: 100%;
left: 0;
}
.search-box input[type="text"], .result{
width: 100%;
box-sizing: border-box;
}
/* Formatting result items */
.result p{
margin: 0;
padding: 7px 10px;
border: 1px solid #CCCCCC;
border-top: none;

Prepared by : G SRIKANTH REDDY Page 15


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

cursor: pointer;
}
.result p:hover{
background: #f2f2f2;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input", function(){
/* Get input value on change */
var inputVal = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(inputVal.length){
$.get("backend-search.php", {term: inputVal}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});

// Set search input value on click of result item


$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
</head>
<body>
<div class="search-box">
<input type="text" autocomplete="off" placeholder="Search country..." />
<div class="result"></div>
</div>
</body>
</html>

Prepared by : G SRIKANTH REDDY Page 16


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

Processing Search Query in Backend


<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");

// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

if(isset($_REQUEST['term'])){
// Prepare a select statement
$sql = "SELECT * FROM countries WHERE name LIKE ?";

if($stmt = mysqli_prepare($link, $sql)){


// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_term);

// Set parameters
$param_term = $_REQUEST['term'] . '%';

// Attempt to execute the prepared statement


if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);

// Check number of rows in the result set


if(mysqli_num_rows($result) > 0){
// Fetch result rows as an associative array
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<p>" . $row["name"] . "</p>";
}
} else{
echo "<p>No matches found</p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}

// Close statement
mysqli_stmt_close($stmt);
}

// close connection

Prepared by : G SRIKANTH REDDY Page 17


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

mysqli_close($link);
?>

Experiment 07:
a) Write a PHP program to upload file into web server.
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {

Prepared by : G SRIKANTH REDDY Page 18


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been
uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>

Experiment 07:
b) Write a PHP program to upload image into database.
Step 1 : Create a simple HTML form

In step 1, let's create a simple HTML form.

<form action="saveimage.php" enctype="multipart/form-data" method="post">


<table style="border-collapse: collapse; font: 12px Tahoma;" border="1" cellspacing="5"
cellpadding="5">

<tbody><tr>

<td>
<input name="uploadedimage" type="file">
</td>
</tr>

<tr>
<td>
<input name="Upload Now" type="submit" value="Upload Image">
</td>
</tr>

</tbody></table>

</form>

Step 2 : Create MYSQL Database Table

To create a database table, we need to write a mysql query. If you want you can use
"phpmyadmin" an interface to create tables or database.

CREATE TABLE images_tbl( images_id INT NOT NULL AUTO_INCREMENT, images_path

Prepared by : G SRIKANTH REDDY Page 19


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

VARCHAR(200) NOT NULL, submission_date DATE,PRIMARY KEY (images_id));

Step 3 : Create MYSQL Connection in PHP

We will create a new php file for the connection and lets name it as "mysqlconnect.php". So lets
write mysql connection.

<!--?php
/**********MYSQL Settings****************/
$host="localhost";
$databasename="karma";
$user="root";
$pass="";
/**********MYSQL Settings****************/
$conn=mysql_connect($host,$user,$pass);
if($conn)
{
$db_selected = mysql_select_db($databasename, $conn);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
}
else
{
die('Not connected : ' . mysql_error());
}
?-->

Step 4 : Store Image in Database using PHP

To store uploaded image path in database we will create a new php file name it as
"saveimage.php" because in the "form" tag we gave "action" attribute target path as
"saveimage.php" and in this file ("saveimage.php") all the form-data will be posted.

Let's Code "saveimage.php" file.

First lets include the mysql connection file in top of "saveimage.php" file.
<?php
include("mysqlconnect.php");
?>

Second let' write a simple function which will give us the image extension from a image
type because there are different image types available to upload like"jpeg, gif, png,
bmp" etc. So we have to create a simple function which will return us the image
extension depending on the image-type.
view source

Prepared by : G SRIKANTH REDDY Page 20


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

print
?
?php
function GetImageExtension($imagetype)
{
if(empty($imagetype)) return false;
switch($imagetype)
{
case 'image/bmp': return '.bmp';
case 'image/gif': return '.gif';
case 'image/jpeg': return '.jpg';
case 'image/png': return '.png';
default: return false;
}
}
?

If you want to save an image with new name then only use the above function other
wise you can also get uploaded image name with extension by using the global PHP
$_FILES["uploadedimage"]["name"] variable.
In this example we will be storing an image with new name so we will be using that
above "GetImageExtension()" function.
Let's store an Image in database with new name

<?php
include("mysqlconnect.php");
function GetImageExtension($imagetype)
{
if(empty($imagetype)) return false;
switch($imagetype)
{
case 'image/bmp': return '.bmp';
case 'image/gif': return '.gif';
case 'image/jpeg': return '.jpg';
case 'image/png': return '.png';
default: return false;
} }
if (!empty($_FILES["uploadedimage"]["name"])) {
$file_name=$_FILES["uploadedimage"]["name"];
$temp_name=$_FILES["uploadedimage"]["tmp_name"];
$imgtype=$_FILES["uploadedimage"]["type"];
$ext= GetImageExtension($imgtype);

Prepared by : G SRIKANTH REDDY Page 21


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

$imagename=date("d-m-Y")."-".time().$ext;
$target_path = "images/".$imagename;

if(move_uploaded_file($temp_name, $target_path)) {
$query_upload="INSERT into 'images_tbl' ('images_path','submission_date')
VALUES
('".$target_path."','".date("Y-m-d")."')";

mysql_query($query_upload) or die("error in $query_upload == ---->


".mysql_error());

}else{
exit("Error While uploading image on the server");
}
}
?>

Step 5 : OUTPUT : Display Image From Database using PHP

<?php
include("mysqlconnect.php");
$select_query = "SELECT 'images_path' FROM 'images_tbl' ORDER by 'images_id' DESC";
$sql = mysql_query($select_query) or die(mysql_error());
while($row = mysql_fetch_array($sql,MYSQL_BOTH)){
?>
<table style="border-collapse: collapse; font: 12px Tahoma;" cellspacing="5" cellpadding="5"
border="1">
<tbody><tr>
<td>
<imgsrc="<?php echo $row[" images_path"];="" ?="">" alt="" />">
</td>
</tr>
</tbody></table>
<php
}? >

PYTHON :

Experiment 08:
a) Write a Program to print the Fibonacci sequence using python
# Program to display the Fibonacci sequence up to n-th term where n is provided by the
user

Prepared by : G SRIKANTH REDDY Page 22


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

# change this value for a different result


nterms = 10

# uncomment to take input from the user


#nterms = int(input("How many terms? "))

# first two terms


n1 = 0
n2 = 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
while count < nterms:
print(n1,end=' , ')
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

Experiment 08:
b) Write a Program to display the Armstrong numbers between the specified
ranges.
# Program to check Armstrong numbers in certain interval

lower = 100
upper = 2000

# To take input from the user


# lower = int(input("Enter lower range: "))
# upper = int(input("Enter upper range: "))

for num in range(lower, upper + 1):

# order of number
order = len(str(num))

Prepared by : G SRIKANTH REDDY Page 23


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

# initialize sum
sum = 0

# find the sum of the cube of each digit


temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10

if num == sum:
print(num)

Experiment 08:
c) Write a Program to perform various operations on Tuples and Dictionaries.
my_tuple = ('p','e','r','m','i','t')

# Output: 'p'
print(my_tuple[0])

# Output: 't'
print(my_tuple[5])

# index must be in range


# If you uncomment line 14,
# you will get an error.
# IndexError: list index out of range

#print(my_tuple[6])

# index must be an integer


# If you uncomment line 21,
# you will get an error.
# TypeError: list indices must be integers, not float

#my_tuple[2.0]

# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

# nested index
# Output: 's'
print(n_tuple[0][3])

Prepared by : G SRIKANTH REDDY Page 24


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

# nested index
# Output: 4
print(n_tuple[1][1])

# create a dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}

# remove a particular item


# Output: 16
print(squares.pop(4))

# Output: {1: 1, 2: 4, 3: 9, 5: 25}


print(squares)

# remove an arbitrary item


# Output: (1, 1)
print(squares.popitem())

# Output: {2: 4, 3: 9, 5: 25}


print(squares)

# delete a particular item


del squares[5]

# Output: {2: 4, 3: 9}
print(squares)

# remove all items


squares.clear()

# Output: {}
print(squares)

# delete the dictionary itself


del squares

# Throws Error
# print(squares)

Experiment 08:

Prepared by : G SRIKANTH REDDY Page 25


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

d) Write a program to multiply two matrices using python.

# Program to multiply two matrices using nested loops

# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]

# iterate through rows of X


for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]

for r in result:
print(r)

Experiment 09:
a. Write a Program to make a simple calculator using python
# This function adds two numbers
def add(x, y):
return x + y

# This function subtracts two numbers


def subtract(x, y):
return x - y

# This function multiplies two numbers


def multiply(x, y):
return x * y

Prepared by : G SRIKANTH REDDY Page 26


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

# This function divides two numbers


def divide(x, y):
return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

# Take input from the user


choice = input("Enter choice(1/2/3/4):")

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))

if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))

elif choice == '2':


print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == '3':


print(num1,"*",num2,"=", multiply(num1,num2))

elif choice == '4':


print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")

Experiment 09:
b. Write a program to find maximum element in the list using recursive functions.
def Max(list):
if len(list) == 1:
return list[0]
else:
m = Max(list[1:])
return m if m > list[0] else list[0]

def main():
list = eval(raw_input(" please enter a list of numbers: "))
print("the largest number is: ", Max(list))

Prepared by : G SRIKANTH REDDY Page 27


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

main()

Experiment 09:
c. Write a program to find GCD and LCM of two numbers using functions.
x,y = input("Enter two integer").split()
x,y = [int(x), int(y)] #convert input string to integers

a=x
b=y

while(b != 0 ):
t=b
b=a%b
a=t

hcf = a
lcm = (x*y)/hcf

print("HCF of %d and %d is %d\n" %(x,y,hcf))


print("LCM of %d and %d is %d\n" %(x,y,lcm))

Experiment 10:
a. Write a Program to recursively calculate the sum of natural numbers using
python

# Python program to find the sum of natural numbers up to n using recursive function

defrecur_sum(n):
"""Function to return the sum
of natural numbers using recursion"""
if n <= 1:
return n
else:
return n + recur_sum(n-1)

# change this value for a different result


num = 16

# uncomment to take input from the user

Prepared by : G SRIKANTH REDDY Page 28


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

#num = int(input("Enter a number: "))

if num< 0:
print("Enter a positive number")
else:
print("The sum is",recur_sum(num))
Experiment 10:
b. Write a Program to sort words in alphabetic order using python.

# Program to sort alphabetically the words form a string provided by the user

# change this value for a different result


my_str = "Hello this Is an Example With cased letters"

# uncomment to take input from the user


#my_str = input("Enter a string: ")

# breakdown the string into a list of words


words = my_str.split()

# sort the list


words.sort()

# display the sorted words

print("The sorted words are:")


for word in words:
print(word)

Experiment 10:
c. Write a program to copy the contents from one file to another file.

with open("test.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write(line)
#or go with next program to read and write seperately
#Read from a file #Write to a file

f = open("./read_file.py", "r");
print f f = open("./new.txt", "a");
for line in f.readlines(): value = ('My name is', "Sergio")
print line myString = str(value)
f.write(myString)

Prepared by : G SRIKANTH REDDY Page 29


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

f.close()

Experiment 11:
a. Write a Program to handle Exceptions using python

#exception program 1

#!/usr/bin/python

try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"

# define Python user-defined exceptions


class Error(Exception):
"""Base class for other exceptions"""
pass

class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass

class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass

# our main program


# user guesses a number until he/she gets it right

# you need to guess this number


number = 10

while True:
try:
i_num = int(input("Enter a number: "))
if i_num< number:

Prepared by : G SRIKANTH REDDY Page 30


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

raise ValueTooSmallError
elifi_num> number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
print()
except ValueTooLargeError:
print("This value is too large, try again!")
print()

print("Congratulations! You guessed it correctly.")

Experiment 11:
b. Write a Program to display Powers of 2 Using Anonymous Function using
python

# Python Program to display the powers of 2 using anonymous function

# Change this value for a different result


terms = 10

# Uncomment to take number of terms from user


#terms = int(input("How many terms? "))

# use anonymous function


result = list(map(lambda x: 2 ** x, range(terms)))

# display the result

print("The total terms is:",terms)


for i in range(terms):
print("2 raised to power",i,"is",result[i])

Experiment 12:

Prepared by : G SRIKANTH REDDY Page 31


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

a. Write a Program to create a form controls using tkinter.


#to create a radio button
from tkinter import *

defsel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)

root = Tk()
var = IntVar()
R1 = Radiobutton(root, text="Option 1", variable=var, value=1,command=sel)
R1.pack( anchor = W )

R2 = Radiobutton(root, text="Option 2", variable=var, value=2,command=sel)


R2.pack( anchor = W )

R3 = Radiobutton(root, text="Option 3", variable=var, value=3,command=sel)


R3.pack( anchor = W)

label = Label(root)
label.pack()
root.mainloop()
#program to get a textbox and reset text typed
from tkinter import *
defbuttonPushed():
#print("button pushed")
txt=t.get()
print("text in the box is",txt)
defresetPushed():
t.delete(1,END)
root = Tk()

w = Label(root, text="hello good morning")


w.pack()

b = Button(root, text="click me",command=buttonPushed)


b.pack()

b1 = Button(root, text="reset me",command=resetPushed)


b1.pack()

t = Entry()
t.pack()

root.mainloop()

Prepared by : G SRIKANTH REDDY Page 32


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

Experiment 12:
b. Write a program to access MySQL DB using Python.

from tkinter import *


import tkinter
from tkinter import messagebox
from lib2to3.fixer_util import Number
import MySQLdb
top = tkinter.Tk()
L1 = Label(top, text=”First Name”)
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = LEFT)
L2 = Label(top, text=”Second Name”)
L2.pack( side = LEFT)
E2 = Entry(top, bd =5)
E2.pack(side = LEFT)
”’L3 = Label(top, text=”Answer”)
L3.pack( side = LEFT)
E3 = Entry(top, bd =5)
E3.pack(side = LEFT)”’
defbuttonCallBack(selection):
print(“E1.get()”+E1.get())
print(“E2.get()”+E2.get())
print(“selection”+selection)
a = E1.get()
b = E2.get()
if selection in (‘Insert’):
# Open database connection
db = MySQLdb.connect(“localhost”,”siddhu”,”siddhu”,”siddhutest” )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query
cursor.execute(“SELECT VERSION()”)
# Fetch a single row
data = cursor.fetchone()
print (“Database version : %s ” % data)
# Drop table if it already exist
cursor.execute(“DROP TABLE IF EXISTS SIDDHU_TEST”)
# Create table Example
sql = “””CREATE TABLE SIDDHU_TEST (
FNAME CHAR(20) NOT NULL,
LNAME CHAR(20))”””

Prepared by : G SRIKANTH REDDY Page 33


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

cursor.execute(sql)
# Inserting in Table Example:- Prepare SQL query to INSERT a record into the database
and accept the value dynamic. This is similar to prepare statement which we create.
sql = “INSERT INTO SIDDHU_TEST(FNAME, \
LNAME) \
VALUES (‘%s’, ‘%s’)” % \
(‘siddhu’, ‘dhumale’)
try:
# Execute command
cursor.execute(sql)
# Commit changes
db.commit()
except:
# Rollback if needed
db.rollback()
# disconnect from server
db.close()
print(“Data Inserted properly “+a +”–“+b)
elif selection in (‘Update’):
# Open database connection
db = MySQLdb.connect(“localhost”,”siddhu”,”siddhu”,”siddhutest” )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query
cursor.execute(“SELECT VERSION()”)
# Fetch a single row
data = cursor.fetchone()
print (“Database version : %s ” % data)
# Update Exmaple:- Update record
sql = “UPDATE SIDDHU_TEST SET LNAME = ‘%s'” % (b) +” WHERE FNAME = ‘%s'” % (a)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
db.close()
print(“Data Updated properly “+a +”–“+b)
elif selection in (‘Delete’):
# Open database connection
db = MySQLdb.connect(“localhost”,”siddhu”,”siddhu”,”siddhutest” )
# prepare a cursor object using cursor() method
cursor = db.cursor()

Prepared by : G SRIKANTH REDDY Page 34


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

# execute SQL query


cursor.execute(“SELECT VERSION()”)
# Fetch a single row
data = cursor.fetchone()
print (“Database version : %s ” % data)
# Delete Operation :- Delete Opearations
sql = “DELETE FROM SIDDHU_TEST WHERE FNAME = ‘%s'” % (a)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
db.close()
print(“Data Deleted properly “+a +”–“+b)
else:
# Open database connection
db = MySQLdb.connect(“localhost”,”siddhu”,”siddhu”,”siddhutest” )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query
cursor.execute(“SELECT VERSION()”)
# Fetch a single row
data = cursor.fetchone()
print (“Database version : %s ” % data)
# Select Query Example :- Selecting data from the table.
sql = “SELECT * FROM SIDDHU_TEST \
WHERE FNAME = ‘%s'” % (a)
try:
# Execute the SQL command
cursor.execute(sql)
lname = “”
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
# Now print fetched result
E2.delete(0,’end’)
print (“Value Fetch properly lname=”+lname)
E2.insert(0, lname)
except:
db.close()

Prepared by : G SRIKANTH REDDY Page 35


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

print (“Value Fetch properly”)


BInsert = tkinter.Button(text =’Insert’, command=lambda: buttonCallBack(‘Insert’))
BInsert.pack(side = LEFT)
BUpdate = tkinter.Button(text =’Update’, command=lambda: buttonCallBack(‘Update’))
BUpdate.pack(side = LEFT)
BDelete = tkinter.Button(text =’Delete’, command=lambda: buttonCallBack(‘Delete’))
BDelete.pack(side = LEFT)
BSelect = tkinter.Button(text =’Select’, command=lambda: buttonCallBack(‘Select’))
BSelect.pack(side = LEFT)
label = Label(top)
label.pack()
top.mainloop()

Output:

Experiment 13:
a. Write a JQuery Script to implement hide() and show() effects

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
});
</script>
</head>
<body>

<p>If you click on the "Hide" button, I will disappear.</p>

<button id="hide">Hide</button>
<button id="show">Show</button>

Prepared by : G SRIKANTH REDDY Page 36


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

</body>
</html>

Output:-

Clicking on hide will hide text above button and clicking on show will show the text

Experiment 13:
b. Write a JQuery Script to apply various sliding effects

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("slow");
});
});
</script>

<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}

#panel {
padding: 50px;
display: none;
}
</style>
</head>
<body>

Prepared by : G SRIKANTH REDDY Page 37


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

<div id="flip">Click to slide the panel down or up</div>


<div id="panel">Hello world!</div>

</body>
</html>
Output:-

Clicking on panel we get toggle working and division is slide down

Experiment 14:
a. Write a JQuery script to animate the given image when ever user clicks on a
button.
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>

<script type = "text/javascript" language = "javascript">


$(document).ready(function() {
$(".clickme").click(function(event){
$(".target").toggle('slow', function(){
$(".log").text('Transition Complete');
});
});
});
</script>

Prepared by : G SRIKANTH REDDY Page 38


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

<style>
.clickme{
margin:10px;
padding:12px;
border:2px solid #666;
width:100px;
height:50px;
}
</style>
</head>

<body>
<div class = "content">
<div class = "clickme">Click Me</div>
<div class = "target">
<imgsrc = "./images/jquery.jpg" alt = "jQuery" />
</div>
<div class = "log"></div>
</div>
</body>
</html>

Output:-
Output before animate

After animate

Prepared by : G SRIKANTH REDDY Page 39


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

Experiment 14:
b. Write a JQuery script to apply various CSS effects

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").css({"background-color": "yellow", "font-size": "200%"});
});
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p style="background-color:#ff0000">This is a paragraph.</p>


<p style="background-color:#00ff00">This is a paragraph.</p>
<p style="background-color:#0000ff">This is a paragraph.</p>

<p>This is a paragraph.</p>

<button>Set multiple styles for p</button>

</body>
</html>
Output:-

Prepared by : G SRIKANTH REDDY Page 40


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

After clicking on button we apply same style to all para by css method

Experiment 15:
a. Write a program to apply various filters to transform data.

<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="namesCtrl">

<p>Type a letter in the input field:</p>

Prepared by : G SRIKANTH REDDY Page 41


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

<p><input type="text" ng-model="test"></p>

<ul>
<li ng-repeat="x in names | filter:test">
{{ x }}
</li>
</ul>

</div>

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
'Jani',
'Carl',
'Margareth',
'Hege',
'Joe',
'Gustav',
'Birgit',
'Mary',
'Kai'
];
});
</script>

<p>The list will only consists of names matching the filter.</p>

</body>
</html>
Output:-
Initially before applying filter

Prepared by : G SRIKANTH REDDY Page 42


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

After applying filter

Experiment 15:
b. Write a program to display data in tables in various forms
<html>

<head>
<title>Angular JS Table</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}

table tr:nth-child(odd) {
background-color: #f2f2f2;

Prepared by : G SRIKANTH REDDY Page 43


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

table tr:nth-child(even) {
background-color: #ffffff;
}
</style>

</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "studentController">

<table border = "0">


<tr>
<td>Enter first name:</td>
<td><input type = "text" ng-model = "student.firstName"></td>
</tr>

<tr>
<td>Enter last name: </td>
<td>
<input type = "text" ng-model = "student.lastName">
</td>
</tr>

<tr>
<td>Name: </td>
<td>{{student.fullName()}}</td>
</tr>

<tr>
<td>Subject:</td>

<td>
<table>
<tr>
<th>Name</th>.
<th>Marks</th>
</tr>

<trng-repeat = "subject in student.subjects">


<td>{{ subject.name }}</td>
<td>{{ subject.marks }}</td>
</tr>

Prepared by : G SRIKANTH REDDY Page 44


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

</table>
</td>

</tr>
</table>

</div>

<script>
varmainApp = angular.module("mainApp", []);

mainApp.controller('studentController', function($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fees:500,

subjects:[
{name:'Physics',marks:70},
{name:'Chemistry',marks:80},
{name:'Math',marks:65},
{name:'English',marks:75},
{name:'Hindi',marks:67}
],

fullName: function() {
varstudentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
</script>

</body>
</html>

Output:-

Prepared by : G SRIKANTH REDDY Page 45


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

Experiment 15:
c. Write a program to apply animations

<!DOCTYPE html>
<html>
<style>
div {
transition: all linear 0.5s;
background-color: lightblue;
height: 100px;
width: 100%;
position: relative;
top: 0;
left: 0;
}

.ng-hide {
height: 0;
width: 0;
background-color: transparent;
top:-200px;
left: 200px;
}

</style>
<script

Prepared by : G SRIKANTH REDDY Page 46


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-
animate.js"></script>

<body ng-app="myApp">

<h1>Hide the DIV: <input type="checkbox" ng-model="myCheck"></h1>

<div ng-hide="myCheck"></div>

<script>
var app = angular.module('myApp', ['ngAnimate']);
</script>

</body>
</html>

Output:-

Additional Programs

1. Write a PHP MySQL Program to demonstrate MySQL prepared statement(insert


data)

<?php
//insert query
$link = mysqli_connect('localhost', 'root', 'root', 'srikanth');

/* check connection */
if (!$link) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

Prepared by : G SRIKANTH REDDY Page 47


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

else
echo "connected successfully";

$stmt = mysqli_prepare($link, "INSERT INTO employee VALUES (?, ?, ?, ?)");


mysqli_stmt_bind_param($stmt, 'isii', $sno, $name,$sal,$num);

$sno = 50;
$name = "naveesdfn";
$num = 30;
$sal = 49000;

mysqli_stmt_execute($stmt);

printf("%d Row inserted.\n", mysqli_stmt_affected_rows($stmt));

/* close statement and connection */


mysqli_stmt_close($stmt);

mysqli_close($link);
?>

2. Write a PHP MySQL Program to demonstrate MySQL prepared statement(select


data)

<?php
$link = mysqli_connect('localhost', 'root', 'root', 'srikanth');

/* check connection */
if (!$link) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
else
echo "connected successfully<br>";

Prepared by : G SRIKANTH REDDY Page 48


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

$stmt = mysqli_prepare($link, "select * from employee where salary>?");

$sal=35000;

mysqli_stmt_bind_param($stmt, "i", $sal);

mysqli_stmt_execute($stmt);

mysqli_stmt_bind_result($stmt, $sno, $name, $salary, $deptno);

echomysqli_field_count ($link)."<br>";

while (mysqli_stmt_fetch($stmt)) {
printf ("%d %s %d %d\n<br>", $sno, $name, $salary, $deptno);
}

mysqli_stmt_close($stmt);

mysqli_close($link);
?>

3. Write a PHP MySQL Program to demonstrate MySQL mysqli_fetch_array /


mysqli_fetch_assoc

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "srikanth";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection

Prepared by : G SRIKANTH REDDY Page 49


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
else
echo "Connected successfully<br>";

$query = "SELECT * FROM employee";


$result = mysqli_query($conn, $query);
//$row = mysqli_fetch_ARRAY($result,MYSQLI_BOTH);
while($row = mysqli_fetch_ASSOC($result))
{
//print_r($row);
printf ("idsg is %s name is (%s) %d %d<br>", $row['id'], $row['name'],$row['salary'],
$row['deptno']);
}

?>

4. Write a PHP MySQL Program to demonstrate MySQL mysqli_fetch_all

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "srikanth";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());

Prepared by : G SRIKANTH REDDY Page 50


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

}
else
echo "Connected successfully<br>";

$query = "SELECT * FROM employee";


$result = mysqli_query($conn, $query);

$row = mysqli_fetch_all($result, MYSQLI_NUM);


//print_r($row);
printf ("%s (%s) %d %d\n", $row[0][0], $row[0][1],$row[0][2], $row[0][3]);

?>

5. Write a PHP MySQL Program to demonstrate MySQL mysqli_multi_query

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "srikanth";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());

Prepared by : G SRIKANTH REDDY Page 51


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

}
else
echo "Connected successfully<br>";
// now as the db connection is done we may perform the required db operation

$query = "SELECT user,host from mysql.user;";


$query .= "SELECT id,name FROM employee ORDER BY ID desc limit 5,2";

/* execute multi query */


if (mysqli_multi_query($conn, $query)) {
do {
/* store first result set , returns a mysqli_result*/
$result = mysqli_store_result($conn);

if ($result!=FALSE) {
//fetch row takes mysqli_result as parameter , fetches one row of
data from result set it as an enumerated array, where each column is stored in an array
offset starting from 0 (zero)
while ($row = mysqli_fetch_row($result)) {
printf("%s %s<br>", $row[0], $row[1]);
}
mysqli_free_result($result);
}

printf("<br>-----------------<br>");
/*

mysqli_more_results($conn) checks if there are any more query results


from a multi query

Returns TRUE if one or more result sets are available from a previous call
to mysqli_multi_query(), otherwise FALSE

*/

/*

mysqli_next_result Prepares next result from multi_query

Returns TRUE on success or FALSE on failure.


*/

Prepared by : G SRIKANTH REDDY Page 52


OPEN SOURCE TECHNOLOGIES LAB MANUAL (A3606)

} while (mysqli_more_results($conn) &&mysqli_next_result($conn));


}

/* close connection */
mysqli_close($conn);

?>

Prepared by : G SRIKANTH REDDY Page 53

You might also like