· 6 years ago · Oct 22, 2019, 04:38 AM
1VARDHAMAN COLLEGE OF ENGINEERING
2(Autonomous)
3DEPARTMENT OF COMPUTER SCIENCE AND TECHNOLOGY
4Shamshabad-501218, Hyderabad
5
6
7OPEN SOURCE TECHNOLOGIES
8LAB MANUAL
9VII Semester
10A3606
11Prepared by
12G SRIKANTH REDDY (Associate Professor, IT Dept)
13D GANESH (Assistant Professor, CSE Dept)
14
15
16
17
18
19
20
21
22LIST OF EXPERIMENTS
23Mysql: EXPERIMENT 1
24 a) Performing basic DML , DDL commands using Mysql
25 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 coordinated 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 pre- requisites modules and some degree programs 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
26 ▪ College code
27 ▪ College Name
28 ▪ College Location
29 ▪ Seat Distribution
30Answer to the following Queries:
31 i. Comprehendthedatagiveninthecasestudybycreatingrespectivetableswithprimarykeysand foreign keys wherever required.
32 ii. Insert values into the tables created (Be vigilant about Master-Slave tables).
33 iii. Display the Students who have taken M.Sc course.
34 iv. Display the Module code and Number of Modules taught by each Lecturer.
35 v. Retrieve the Lecturer names who are not Module Leaders.
36 vi. Display the Department name which offers ‘English’ module.
37 vii. Retrieve the Pre requisite Courses offered by every Department (with Department names).
38 viii. Present the Lecturer ID and Name who teaches ‘Mathematics’.
39 ix. Discover the number of years a Module is taught.
40 x. List out all the Faculties who work for ‘Statistics’ Department
41EXPERIMENT 2:
42 a) EMPLOYEE AND DEPARTMENT DATABASE
43The 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 of experience. Construct the database design with that there is no redundancy.
44Answer to the following Queries:
45 i. List Employee Details.
46 ii. List the department Details.
47 iii. Update emp table and change employee name, ADAMS to ADAM.
48 iv. Update emp table and change sal, comm to2000&500toanemployeeno7844.
49 v. Select deptno, dname, of deptno>10andlocatedin‘NEWYORK’.
50 vi. List all employee details who belongs to deptno=10andwhosejobisclerk.
51 vii. Find the total number of clerks in department 10?
52 viii. Find the average salary of employees?
53 ix. List all employees of their average salaries.
54 x. Find minimum salary paid employee and employee details with that salaries?
55 xi. Find the name of employee which starts with ‘A’ and end with ‘N’?
56 xii. List all employees who have salary greater than 15000 in the order of department number?
57 xiii. List deptno, dname, min (sal) for all departments?
58 xiv. Display all employee names, number, dept name & location of all employees?
59 xv. Findemployeenameemployeenumber,theirsalarywhowerehiredafter01/02/97
60PHP:
61EXPERIMENT 3:
62 a) Write a PHP program to validate form contents using regular expressions.
63 b) Write a PHP program to merge the contents of two files and store into another file.
64EXPERIMENT 4:
65 a) Write a PHP program to create a ZIP file using PHP.
66 b) Write a PHP program to validate IP address, Integer and E-mail using filters.
67EXPERIMENT 5:
68 a) Write a PHP program to retrieve the data from Mysql database.
69 b) Write a PHP program to implement sessions and cookies.
70EXPERIMENT 6:
71 a) Write a PHP program to authenticate login credentials.
72 b) Write a PHP program to insert the contents of student registration form (Rno , name ,branch ,age , email ,and phone)into Mysql database.
73 c) Write an AJAX script to perform search operation on Mysql database.
74EXPERIMENT 7:
75 a) Write a PHP program to upload file into web server.
76 b) Write a PHP program to upload image into database.
77PYTHON:
78EXPERIMENT 8:
79 a) Write a Program to print the Fibonacci sequence using python.
80 b) Write a Program to display the Armstrong numbers between the specified ranges.
81 c) Write a Program to perform various operations on Tuples and Dictionaries.
82 d) Write a program to multiply two matrices using python.
83EXPERIMENT 9:
84 a) Write a Program to make a simple calculator using python.
85 b) Write a program to find maximum element in the list using recursive functions.
86 c) Write a program to find GCD and LCM of two numbers using functions.
87EXPERIMENT 10:
88 a) Write a Program to recursively calculate the sum of natural numbers using python.
89 b) Write a Program to sort words in alphabetic order using python.
90 c) Write a program to copy the contents from one file to another file.
91EXPERIMENT 11:
92 a) Write a Program to handle Exceptions using python.
93 b) Write a Program to display Powers of 2 Using Anonymous Function using python.
94EXPERIMENT 12:
95 a) Write a Program to create a form controls using tkinter.
96 b) Write a program to access Mysql DB using Python.
97JQUERY:
98EXPERIMENT 13
99 a) Write a JQuery Script to implement hide() and show()effects.
100 b) Write a JQuery Script to apply various sliding effects.
101EXPERIMENT 14:
102 a) Write a JQuery script to animate the given image whenever user clicks on a button.
103 b) Write a JQuery script to apply various CSS effects.
104AngularJS:
105EXPERIMENT 15:
106 a) Write a program to apply various filters to transform data.
107 b) Write a program to display data in tables in various forms.
108 c) Write a program to apply animations.
109
110
111
112
113
114Experiment 01:
115Student will be practicing the queries of this case study based on the Database Management Systems Laboratory knowledge
116Experiment 02:
117Employee table
118
119
120Dept table
121
122
123Queries
124List employee details.
125SQL> select * from emp2b4;
126List the department Details.
127SQL> select * from dept2b4;
128Update emp2b4 table and change employee name, ADAMS to ADAM.
129SQL> update emp2b4 set ename='ADAM' where empno=7876;
130Update emp2b4 table and change sal,comm. to 2000 & 500 respectively for an
131employee with empno 7844.
132SQL> update emp2b4 set sal=2000, comm=500 where empno=7844;
133Select deptno, dname ,of deptno>10 and located in ‘NEWYORK’.
134SQL> select deptno,dname from dept2b4 where deptno>10 and loc='NEW YORK';
135List all employee details whose empno=10 and whose job is clerk.
136SQL> select * from emp2b4 where deptno=10 and job='CLERK';
137List all employee hired during 1981?
138SQL> select * from emp2b4 where hiredate between '01-JAN-1981' and '31-DEC-1981';
139List all empno, ename of all employee in format “empno ename”.
140SQL> select empno,ename from emp2b4;
141Find the total number of clerks in department 10.
142SQL> select count(*),deptno from emp2b4 where job='CLERK' group by deptno having
143deptno=10;
144Find the average salary of employees
145SQL> select avg(sal) from emp2b4;
146Find minimum salary paid employee and employee details with that salaries.
147SQL> select * from emp2b4 where sal=(select min(sal) from emp2b4);
148Find the name of employee which starts with ‘A’ and end with ‘N’
149SQL> select e.ename from emp2b4 e where e.ename like 'A%N';
150List all employees who have a salary greater than 1500 in the order of department
151number.
152SQL> select * from emp2b4 where sal>1500 order by deptno;
153List deptno , dname ,min(sal) for all departments.
154SQL> select d.deptno,d.dname,min(e.sal) from dept2b4 d,emp2b4 e where
155d.deptno=e.deptno group by d.deptno,d.dname;
156List all employees deptno.-wise.
157SQL> select ename,deptno from emp2b4 order by deptno;
158Display all employee names, number, deptname & location of all employees.
159SQL> select e.ename,e.empno,d.dname,d.loc from emp2b4 e,dept2b4 d where
160d.deptno=e.deptno;
161Find the employees belongs to the research department.
162SQL> select * from emp2b4 e where e.deptno=(select d.deptno from dept2b4 d where
163d.dname='RESEARCH');
164Find employee name employee number, their salary who were hired after 01/02/97.
165SQL> select ename,empno,sal from emp2b4 where hiredate>'01-FEB-1997';
166Find the second maximum salary of employee table.
167SQL> select max(sal) from emp2b4 where sal<(select max(sal) from emp2b4);
168Find employee name from employee table whose manager is NULL.
169SQL> select ename from emp2b4 where mgr is null;
170Experiment 03:
171 a) Write a PHP program to validate form contents using regular expressions.
172Processing page
173<?php
174if($_POST)
175{
176$name = $_POST['name'];
177$email = $_POST['email'];
178$username = $_POST['username'];
179$password = $_POST['password'];
180$gender = $_POST['gender'];
181if (eregi('^[A-Za-z0-9 ]{3,20}$',$name)) // Full Name
182{
183$valid_name=$name;
184}
185else
186{
187$error_name='Enter valid Name.';
188}
189if (eregi('^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$', $email)) // Email
190{
191$valid_email=$email;
192}
193else
194{
195$error_email='Enter valid Email.';
196}
197if (eregi('^[A-Za-z0-9_]{3,20}$',$username)) // Usename min 2 char max 20 char
198{
199$valid_username=$username;
200}
201else
202{
203$error_username='Enter valid Username min 3 Chars.';
204}
205if (eregi('^[A-Za-z0-9!@#$%^&*()_]{6,20}$',$password))
206{
207$valid_password=$password;
208}
209else
210{
211$error_password='Enter valid Password min 6 Chars.';
212}
213if ($gender==0) // Gender
214{
215$error_gender='Select Gender';
216}
217else
218{
219$valid_gender=$gender;
220}
221if((strlen($valid_name)>0)&&(strlen($valid_email)>0)
222&&(strlen($valid_username)>0)&&(strlen($valid_password)>0) && $valid_gender>0 )
223{
224mysql_query(" SQL insert statement ");
225header("Location: thanks.html");
226}
227else{ }
228} ?>
229Front page
230<php include("validation.php"); ?>
231<form method="post" action="" name="form">
232Full name : <input type="text" name="name" value="<?php echo $valid_name; ?>" />
233<?php echo $error_name; ?>
234Email : <input type="text" name="name" value="<?php echo $valid_email; ?>" />
235<?php echo $error_email; ?>
236Username : <input type="text" name="name" value="<?php echo $valid_username; ?>" />
237<?php echo $error_username; ?>
238Password : <input type="password" name="name" value="<?php echo $valid_password; ?>" />
239<?php echo $error_password; ?>
240Gender : <select name="gender">
241<option value="0">Gender</option>
242<option value="1">Male</option>
243<option value="2">Female</option> </select>
244<?php echo $error_gender; ?> </form>
245 b) Write a PHP program to merge the contents of two files and store into another file.
246$lines = file('Country.txt');
247$lines2 = file('countryenglish.txt');
248foreach ($lines as $key => $val) {
249 $lines[$key] = $val.$lines2[$key];
250}
251file_put_contents('countryenglish2.txt', implode("\n", $lines));
252Experiment 04:
253 a) Write a PHP program to create a ZIP file using PHP.
254/* creates a compressed zip file */
255function create_zip($files = array(),$destination = '',$overwrite = false) {
256 //if the zip file already exists and overwrite is false, return false
257 if(file_exists($destination) && !$overwrite) { return false; }
258 //vars
259 $valid_files = array();
260 //if files were passed in...
261 if(is_array($files)) {
262 //cycle through each file
263 foreach($files as $file) {
264 //make sure the file exists
265 if(file_exists($file)) {
266 $valid_files[] = $file;
267 }
268 }
269 }
270 //if we have good files...
271 if(count($valid_files)) {
272 //create the archive
273 $zip = new ZipArchive();
274 if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
275 return false;
276 }
277 //add the files
278 foreach($valid_files as $file) {
279 $zip->addFile($file,$file);
280 }
281 //debug
282 //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
283
284 $zip->close(); //close the zip -- done!
285
286 return file_exists($destination); //check to make sure the file exists
287 }
288 else
289 {
290 return false;
291 }
292}
293 b) Write a PHP program to validate IP address, Integer and E-mail using filters.
294IP address
295<?php
296$ip = "127.0.0.1";
297if (!filter_var($ip, FILTER_VALIDATE_IP) === false) {
298 echo("$ip is a valid IP address");
299} else {
300 echo("$ip is not a valid IP address");
301}
302?>
303Email address
304<?php
305$email = "john.doe@example.com";
306// Remove all illegal characters from email
307$email = filter_var($email, FILTER_SANITIZE_EMAIL);
308// Validate e-mail
309if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
310 echo("$email is a valid email address");
311} else {
312 echo("$email is not a valid email address");
313}
314?>
315
316Integer
317<?php
318$int = 100;
319if (!filter_var($int, FILTER_VALIDATE_INT) === false) {
320 echo("Integer is valid");
321} else {
322 echo("Integer is not valid");
323}
324?>
325
326
327
328
329
330
331
332
333
334Experiment 05:
335 a) Write a PHP program to retrieve the data from MySQL database
336<?php
337$servername = "localhost";
338$username = "username";
339$password = "password";
340$dbname = "myDB";
341// Create connection
342$conn = mysqli_connect($servername, $username, $password, $dbname);
343// Check connection
344if (!$conn) {
345 die("Connection failed: " . mysqli_connect_error()); }
346$sql = "SELECT id, firstname, lastname FROM MyGuests";
347$result = mysqli_query($conn, $sql);
348if (mysqli_num_rows($result) > 0) {
349 // output data of each row
350 while($row = mysqli_fetch_assoc($result)) {
351 echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
352 } } else {
353 echo "0 results"; }
354mysqli_close($conn); ?>
355
356 b) Write a PHP program to implement sessions and cookies.
357Creating a cookie
358<?php
359 setcookie("user_name", "Guru99", time()+ 60,'/'); // expires after 60 seconds
360 echo 'the cookie has been set for 60 seconds'; ?>
361Retrieving a cookie
362<?php print_r($_COOKIE); ?>
363Deleting a cookie
364<?php setcookie("user_name", "Guru99", time() - 360,'/'); ?>
365Creating and accessing a session
366<?php session_start(); //start the PHP_session function
367if(isset($_SESSION['page_count']))
368{ $_SESSION['page_count'] += 1; }
369else
370{ $_SESSION['page_count'] = 1; }
371 echo 'You are visitor number ' . $_SESSION['page_count']; ?>
372Destroying a session
373<?php session_destroy(); //destroy entire session ?>
374Experiment 06:
375 a) Write a PHP program to authenticate login credentials.
376HTML page
377<form name="frmUser" method="post" action="">
378 <div class="message"><?php if($message!="") { echo $message; } ?></div>
379 <table border="0" cellpadding="10" cellspacing="1" width="500" align="center" class="tblLogin">
380 <tr class="tableheader">
381 <td align="center" colspan="2">Enter Login Details</td>
382 </tr>
383 <tr class="tablerow">
384 <td>
385 <input type="text" name="userName" placeholder="User Name" class="login-input"></td> </tr>
386 <tr class="tablerow">
387 <td>
388 <input type="password" name="password" placeholder="Password" class="login-input"> </td> </tr>
389 <tr class="tableheader">
390 <td align="center" colspan="2"><input type="submit" name="submit" value="Submit" class="btnSubmit"></td>
391 </tr>
392 </table>
393</form>
394
395PHP program
396<?php
397$message="";
398if(count($_POST)>0) {
399 $conn = mysqli_connect("localhost","root","","phppot_examples");
400 $result = mysqli_query($conn,"SELECT * FROM users WHERE user_name='" . $_POST["userName"] . "' and password = '". $_POST["password"]."'");
401 $count = mysqli_num_rows($result);
402 if($count==0) {
403 $message = "Invalid Username or Password!";
404 } else {
405 $message = "You are successfully authenticated!"; } }
406?>
407
408 b) Write a PHP program to insert the contents of student registration form (Rno, name, branch, age, email, and phone) into MySQL database.
409
410HTML Page for registration
411<html>
412<body>
413<form action="2a.php" method="post">
414NA:<input type="text" name="name"/></br>
415S1:<input type="text" name="rno"/></br>
416S2:<input type="text" name="branch"/></br>
417S3:<input type="text" name="age"/></br>
418S4:<input type="text" name="email"/></br>
419S5:<input type="text" name="phone"/></br>
420</br>
421<input type="submit"/>
422</form> </body> </html>
423Inserting values into database
424<?php
425session_start();
426$servername = "localhost";
427$username = "root";
428$password = "root";
429$dbname = "mahi";
430if(isset($_SESSION['val'])) {
431 $_SESSION["val"] = $_SESSION["val"]+1;
432}
433else
434$_SESSION["val"] = 1;
435echo($_SESSION["val"]);
436$conn = mysqli_connect($servername, $username, $password, $dbname);
437if (!$conn) {
438die("Connection failed: " . mysqli_connect_error());
439}
440$total=0;
441$name=$_POST["name"];
442$s1=$_POST["rno"];
443$s2=$_POST["age"];
444$s3=$_POST["branch"];
445$s4=$_POST["email"];
446$s5=$_POST["phone"];
447$sql = "INSERT INTO students VALUES ('$name',’$s1’,’$s2’,’$s3’,’$s4’,’$s5’)";
448mysqli_query($conn, $sql);
449if ($_SESSION["val"]>=6) { session_destroy();
450 header("Location: red.php"); }
451else
452{ header("Location: 2lab.html"); }
453mysqli_close($conn); ?>
454
455
456 c) Write an AJAX script to perform search operation on MySQL database.
457Get the table ready
458CREATE TABLE countries (
459 id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
460 name VARCHAR(50) NOT NULL
461);
462Creating the Search Form
463<!DOCTYPE html>
464<html lang="en">
465<head>
466<meta charset="UTF-8">
467<title>PHP Live MySQL Database Search</title>
468<style type="text/css">
469 body{
470 font-family: Arail, sans-serif;
471 }
472 /* Formatting search box */
473 .search-box{
474 width: 300px;
475 position: relative;
476 display: inline-block;
477 font-size: 14px;
478 }
479 .search-box input[type="text"]{
480 height: 32px;
481 padding: 5px 10px;
482 border: 1px solid #CCCCCC;
483 font-size: 14px;
484 }
485 .result{
486 position: absolute;
487 z-index: 999;
488 top: 100%;
489 left: 0;
490 }
491 .search-box input[type="text"], .result{
492 width: 100%;
493 box-sizing: border-box;
494 }
495 /* Formatting result items */
496 .result p{
497 margin: 0;
498 padding: 7px 10px;
499 border: 1px solid #CCCCCC;
500 border-top: none;
501 cursor: pointer;
502 }
503 .result p:hover{
504 background: #f2f2f2;
505 }
506</style>
507<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
508<script type="text/javascript">
509$(document).ready(function(){
510 $('.search-box input[type="text"]').on("keyup input", function(){
511 /* Get input value on change */
512 var inputVal = $(this).val();
513 var resultDropdown = $(this).siblings(".result");
514 if(inputVal.length){
515 $.get("backend-search.php", {term: inputVal}).done(function(data){
516 // Display the returned data in browser
517 resultDropdown.html(data);
518 });
519 } else{
520 resultDropdown.empty();
521 }
522 });
523 // Set search input value on click of result item
524 $(document).on("click", ".result p", function(){
525 $(this).parents(".search-box").find('input[type="text"]').val($(this).text());
526 $(this).parent(".result").empty();
527 });
528});
529</script> </head>
530<body>
531 <div class="search-box">
532 <input type="text" autocomplete="off" placeholder="Search country..." />
533 <div class="result"></div>
534 </div> </body> </html>
535
536
537Processing Search Query in Backend
538<?php
539/* Attempt MySQL server connection. Assuming you are running MySQL
540server with default setting (user 'root' with no password) */
541$link = mysqli_connect("localhost", "root", "", "demo");
542// Check connection
543if($link === false){
544 die("ERROR: Could not connect. " . mysqli_connect_error());
545}
546if(isset($_REQUEST['term'])){
547 // Prepare a select statement
548 $sql = "SELECT * FROM countries WHERE name LIKE ?";
549
550 if($stmt = mysqli_prepare($link, $sql)){
551 // Bind variables to the prepared statement as parameters
552 mysqli_stmt_bind_param($stmt, "s", $param_term);
553
554 // Set parameters
555 $param_term = $_REQUEST['term'] . '%';
556 // Attempt to execute the prepared statement
557 if(mysqli_stmt_execute($stmt)){
558 $result = mysqli_stmt_get_result($stmt);
559 // Check number of rows in the result set
560 if(mysqli_num_rows($result) > 0){
561 // Fetch result rows as an associative array
562 while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
563 echo "<p>" . $row["name"] . "</p>";
564 }
565 } else{
566 echo "<p>No matches found</p>";
567 }
568 } else{
569 echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
570 }
571 }
572 // Close statement
573 mysqli_stmt_close($stmt);
574} // close connection
575mysqli_close($link);
576?>
577Experiment 07:
578 a) Write a PHP program to upload file into web server.
579<?php
580$target_dir = "uploads/";
581$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
582$uploadOk = 1;
583$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
584// Check if image file is a actual image or fake image
585if(isset($_POST["submit"])) {
586 $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
587 if($check !== false) {
588 echo "File is an image - " . $check["mime"] . ".";
589 $uploadOk = 1;
590 } else {
591 echo "File is not an image.";
592 $uploadOk = 0;
593 }
594}
595// Check if file already exists
596if (file_exists($target_file)) {
597 echo "Sorry, file already exists.";
598 $uploadOk = 0;
599}
600// Check file size
601if ($_FILES["fileToUpload"]["size"] > 500000) {
602 echo "Sorry, your file is too large.";
603 $uploadOk = 0;
604}
605// Allow certain file formats
606if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
607&& $imageFileType != "gif" ) {
608 echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
609 $uploadOk = 0;
610}
611// Check if $uploadOk is set to 0 by an error
612if ($uploadOk == 0) {
613 echo "Sorry, your file was not uploaded.";
614// if everything is ok, try to upload file
615} else {
616 if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
617 echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
618 } else {
619 echo "Sorry, there was an error uploading your file.";
620 }
621}
622?>
623
624 b) Write a PHP program to upload image into database.
625Step 1 : Create a simple HTML form
626In step 1, let's create a simple HTML form.
627<form action="saveimage.php" enctype="multipart/form-data" method="post">
628<table style="border-collapse: collapse; font: 12px Tahoma;" border="1" cellspacing="5" cellpadding="5">
629
630<tbody><tr>
631
632 <td>
633 <input name="uploadedimage" type="file">
634 </td>
635 </tr>
636
637 <tr>
638 <td>
639 <input name="Upload Now" type="submit" value="Upload Image">
640 </td>
641 </tr>
642
643</tbody></table>
644
645</form>
646
647Step 2 : Create MYSQL Database Table
648
649To 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.
650
651CREATE TABLE images_tbl( images_id INT NOT NULL AUTO_INCREMENT, images_path VARCHAR(200) NOT NULL, submission_date DATE,PRIMARY KEY (images_id));
652
653Step 3 : Create MYSQL Connection in PHP
654
655We will create a new php file for the connection and lets name it as "mysqlconnect.php". So lets write mysql connection.
656
657<!--?php
658 /**********MYSQL Settings****************/
659 $host="localhost";
660 $databasename="karma";
661 $user="root";
662 $pass="";
663 /**********MYSQL Settings****************/
664 $conn=mysql_connect($host,$user,$pass);
665 if($conn)
666 {
667 $db_selected = mysql_select_db($databasename, $conn);
668 if (!$db_selected) {
669 die ('Can\'t use foo : ' . mysql_error());
670 }
671 }
672 else
673 {
674 die('Not connected : ' . mysql_error());
675 }
676 ?-->
677
678
679Step 4 : Store Image in Database using PHP
680
681To 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.
682
683Let's Code "saveimage.php" file.
684
685First lets include the mysql connection file in top of "saveimage.php" file.
686 <?php
687 include("mysqlconnect.php");
688 ?>
689
690Second 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.
691view source
692print
693?
694 ?php
695 function GetImageExtension($imagetype)
696 {
697 if(empty($imagetype)) return false;
698 switch($imagetype)
699 {
700 case 'image/bmp': return '.bmp';
701 case 'image/gif': return '.gif';
702 case 'image/jpeg': return '.jpg';
703 case 'image/png': return '.png';
704 default: return false;
705 }
706 }
707?
708
709
710
711If 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.
712In this example we will be storing an image with new name so we will be using that above "GetImageExtension()" function.
713Let's store an Image in database with new name
714
715
716<?php
717 include("mysqlconnect.php");
718 function GetImageExtension($imagetype)
719 {
720 if(empty($imagetype)) return false;
721 switch($imagetype)
722 {
723 case 'image/bmp': return '.bmp';
724 case 'image/gif': return '.gif';
725 case 'image/jpeg': return '.jpg';
726 case 'image/png': return '.png';
727 default: return false;
728 } }
729if (!empty($_FILES["uploadedimage"]["name"])) {
730 $file_name=$_FILES["uploadedimage"]["name"];
731 $temp_name=$_FILES["uploadedimage"]["tmp_name"];
732 $imgtype=$_FILES["uploadedimage"]["type"];
733 $ext= GetImageExtension($imgtype);
734 $imagename=date("d-m-Y")."-".time().$ext;
735 $target_path = "images/".$imagename;
736
737 if(move_uploaded_file($temp_name, $target_path)) {
738 $query_upload="INSERT into 'images_tbl' ('images_path','submission_date') VALUES
739 ('".$target_path."','".date("Y-m-d")."')";
740
741 mysql_query($query_upload) or die("error in $query_upload == ----> ".mysql_error());
742
743 }else{
744 exit("Error While uploading image on the server");
745 }
746 }
747 ?>
748Step 5 : OUTPUT : Display Image From Database using PHP
749
750<?php
751include("mysqlconnect.php");
752$select_query = "SELECT 'images_path' FROM 'images_tbl' ORDER by 'images_id' DESC";
753$sql = mysql_query($select_query) or die(mysql_error());
754while($row = mysql_fetch_array($sql,MYSQL_BOTH)){
755?>
756<table style="border-collapse: collapse; font: 12px Tahoma;" cellspacing="5" cellpadding="5" border="1">
757<tbody><tr>
758<td>
759<imgsrc="<?php echo $row[" images_path"];="" ?="">" alt="" />">
760</td>
761</tr>
762</tbody></table>
763<php
764}? >
765
766
767
768
769
770
771
772
773
774PYTHON: Experiment 08
775 a) Write a Program to print the Fibonacci sequence using python
776# Program to display the Fibonacci sequence up to n-th term where n is provided by the user
777
778# change this value for a different result
779nterms = 10
780
781# uncomment to take input from the user
782#nterms = int(input("How many terms? "))
783
784# first two terms
785n1 = 0
786n2 = 1
787count = 0
788
789# check if the number of terms is valid
790if nterms <= 0:
791 print("Please enter a positive integer")
792elif nterms == 1:
793 print("Fibonacci sequence upto",nterms,":")
794 print(n1)
795else:
796 print("Fibonacci sequence upto",nterms,":")
797 while count < nterms:
798 print(n1,end=' , ')
799 nth = n1 + n2
800 # update values
801 n1 = n2
802 n2 = nth
803 count += 1
804
805 b) Write a Program to display the Armstrong numbers between the specified ranges.
806# Program to check Armstrong numbers in certain interval
807
808lower = 100
809upper = 2000
810
811# To take input from the user
812# lower = int(input("Enter lower range: "))
813# upper = int(input("Enter upper range: "))
814
815for num in range(lower, upper + 1):
816
817 # order of number
818 order = len(str(num))
819
820 # initialize sum
821 sum = 0
822
823 # find the sum of the cube of each digit
824 temp = num
825 while temp > 0:
826 digit = temp % 10
827 sum += digit ** order
828 temp //= 10
829
830 if num == sum:
831 print(num)
832
833 c) Write a Program to perform various operations on Tuples and Dictionaries.
834my_tuple = ('p','e','r','m','i','t')
835
836# Output: 'p'
837print(my_tuple[0])
838
839# Output: 't'
840print(my_tuple[5])
841
842# index must be in range
843# If you uncomment line 14,
844# you will get an error.
845# IndexError: list index out of range
846
847#print(my_tuple[6])
848
849# index must be an integer
850# If you uncomment line 21,
851# you will get an error.
852# TypeError: list indices must be integers, not float
853
854#my_tuple[2.0]
855
856# nested tuple
857n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
858
859# nested index
860# Output: 's'
861print(n_tuple[0][3])
862
863# nested index
864# Output: 4
865print(n_tuple[1][1])
866
867# create a dictionary
868squares = {1:1, 2:4, 3:9, 4:16, 5:25}
869
870# remove a particular item
871# Output: 16
872print(squares.pop(4))
873
874# Output: {1: 1, 2: 4, 3: 9, 5: 25}
875print(squares)
876
877# remove an arbitrary item
878# Output: (1, 1)
879print(squares.popitem())
880
881# Output: {2: 4, 3: 9, 5: 25}
882print(squares)
883
884# delete a particular item
885del squares[5]
886
887# Output: {2: 4, 3: 9}
888print(squares)
889
890# remove all items
891squares.clear()
892
893# Output: {}
894print(squares)
895
896# delete the dictionary itself
897del squares
898
899# Throws Error
900# print(squares)
901
902
903 d) Write a program to multiply two matrices using python.
904
905# Program to multiply two matrices using nested loops
906
907# 3x3 matrix
908X = [[12,7,3],
909 [4 ,5,6],
910 [7 ,8,9]]
911# 3x4 matrix
912Y = [[5,8,1,2],
913 [6,7,3,0],
914 [4,5,9,1]]
915# result is 3x4
916result = [[0,0,0,0],
917 [0,0,0,0],
918 [0,0,0,0]]
919
920# iterate through rows of X
921for i in range(len(X)):
922 # iterate through columns of Y
923 for j in range(len(Y[0])):
924 # iterate through rows of Y
925 for k in range(len(Y)):
926 result[i][j] += X[i][k] * Y[k][j]
927
928for r in result:
929 print(r)
930
931
932
933
934
935
936
937
938
939
940Experiment 09:
941 a. Write a Program to make a simple calculator using python
942# This function adds two numbers
943def add(x, y):
944 return x + y
945
946# This function subtracts two numbers
947def subtract(x, y):
948 return x - y
949
950# This function multiplies two numbers
951def multiply(x, y):
952 return x * y
953
954# This function divides two numbers
955def divide(x, y):
956 return x / y
957print("Select operation.")
958print("1.Add")
959print("2.Subtract")
960print("3.Multiply")
961print("4.Divide")
962
963# Take input from the user
964choice = input("Enter choice(1/2/3/4):")
965
966num1 = int(input("Enter first number: "))
967num2 = int(input("Enter second number: "))
968
969if choice == '1':
970 print(num1,"+",num2,"=", add(num1,num2))
971
972elif choice == '2':
973 print(num1,"-",num2,"=", subtract(num1,num2))
974
975elif choice == '3':
976 print(num1,"*",num2,"=", multiply(num1,num2))
977
978elif choice == '4':
979 print(num1,"/",num2,"=", divide(num1,num2))
980else:
981 print("Invalid input")
982 b. Write a program to find maximum element in the list using recursive functions.
983def Max(list):
984 if len(list) == 1:
985 return list[0]
986 else:
987 m = Max(list[1:])
988 return m if m > list[0] else list[0]
989
990def main():
991 list = eval(raw_input(" please enter a list of numbers: "))
992 print("the largest number is: ", Max(list))
993
994main()
995
996 c. Write a program to find GCD and LCM of two numbers using functions.
997x,y = input("Enter two integer").split()
998x,y = [int(x), int(y)] #convert input string to integers
999
1000
1001a = x
1002b = y
1003
1004while(b != 0 ):
1005 t = b
1006 b = a % b
1007 a = t
1008
1009hcf = a
1010lcm = (x*y)/hcf
1011
1012print("HCF of %d and %d is %d\n" %(x,y,hcf))
1013print("LCM of %d and %d is %d\n" %(x,y,lcm))
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023Experiment 10:
1024 a. Write a Program to recursively calculate the sum of natural numbers using python
1025
1026# Python program to find the sum of natural numbers up to n using recursive function
1027
1028defrecur_sum(n):
1029 """Function to return the sum
1030 of natural numbers using recursion"""
1031 if n <= 1:
1032 return n
1033 else:
1034 return n + recur_sum(n-1)
1035
1036# change this value for a different result
1037num = 16
1038
1039# uncomment to take input from the user
1040#num = int(input("Enter a number: "))
1041
1042if num< 0:
1043 print("Enter a positive number")
1044else:
1045 print("The sum is",recur_sum(num))
1046 b. Write a Program to sort words in alphabetic order using python.
1047
1048# Program to sort alphabetically the words form a string provided by the user
1049
1050# change this value for a different result
1051my_str = "Hello this Is an Example With cased letters"
1052
1053# uncomment to take input from the user
1054#my_str = input("Enter a string: ")
1055
1056# breakdown the string into a list of words
1057words = my_str.split()
1058
1059# sort the list
1060words.sort()
1061
1062# display the sorted words
1063
1064print("The sorted words are:")
1065for word in words:
1066 print(word)
1067
1068 c. Write a program to copy the contents from one file to another file.
1069
1070with open("test.txt") as f:
1071 with open("out.txt", "w") as f1:
1072 for line in f:
1073 f1.write(line)
1074#or go with next program to read and write seperately
1075#Read from a file
1076
1077f = open("./read_file.py", "r");
1078print f
1079for line in f.readlines():
1080 print line
1081
1082#Write to a file
1083
1084
1085f = open("./new.txt", "a");
1086value = ('My name is', "Sergio")
1087myString = str(value)
1088f.write(myString)
1089f.close()
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114Experiment 11:
1115 a. Write a Program to handle Exceptions using python
1116
1117#exception program 1
1118
1119#!/usr/bin/python
1120
1121try:
1122fh = open("testfile", "r")
1123fh.write("This is my test file for exception handling!!")
1124except IOError:
1125 print "Error: can\'t find file or read data"
1126else:
1127 print "Written content in the file successfully"
1128
1129# define Python user-defined exceptions
1130class Error(Exception):
1131 """Base class for other exceptions"""
1132 pass
1133
1134class ValueTooSmallError(Error):
1135 """Raised when the input value is too small"""
1136 pass
1137
1138class ValueTooLargeError(Error):
1139 """Raised when the input value is too large"""
1140 pass
1141
1142# our main program
1143# user guesses a number until he/she gets it right
1144
1145# you need to guess this number
1146number = 10
1147
1148while True:
1149 try:
1150i_num = int(input("Enter a number: "))
1151 if i_num< number:
1152 raise ValueTooSmallError
1153elifi_num> number:
1154 raise ValueTooLargeError
1155 break
1156 except ValueTooSmallError:
1157print("This value is too small, try again!")
1158 print()
1159 except ValueTooLargeError:
1160print("This value is too large, try again!")
1161 print()
1162
1163print("Congratulations! You guessed it correctly.")
1164
1165 b. Write a Program to display Powers of 2 Using Anonymous Function using python
1166
1167# Python Program to display the powers of 2 using anonymous function
1168
1169# Change this value for a different result
1170terms = 10
1171
1172# Uncomment to take number of terms from user
1173#terms = int(input("How many terms? "))
1174
1175# use anonymous function
1176result = list(map(lambda x: 2 ** x, range(terms)))
1177
1178# display the result
1179
1180print("The total terms is:",terms)
1181for i in range(terms):
1182 print("2 raised to power",i,"is",result[i])
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198Experiment 12:
1199 a. Write a Program to create a form controls using tkinter.
1200#to create a radio button
1201from tkinter import *
1202
1203defsel():
1204 selection = "You selected the option " + str(var.get())
1205label.config(text = selection)
1206
1207root = Tk()
1208var = IntVar()
1209R1 = Radiobutton(root, text="Option 1", variable=var, value=1,command=sel)
1210R1.pack( anchor = W )
1211
1212R2 = Radiobutton(root, text="Option 2", variable=var, value=2,command=sel)
1213R2.pack( anchor = W )
1214
1215R3 = Radiobutton(root, text="Option 3", variable=var, value=3,command=sel)
1216R3.pack( anchor = W)
1217
1218label = Label(root)
1219label.pack()
1220root.mainloop()
1221#program to get a textbox and reset text typed
1222from tkinter import *
1223defbuttonPushed():
1224 #print("button pushed")
1225 txt=t.get()
1226 print("text in the box is",txt)
1227defresetPushed():
1228t.delete(1,END)
1229root = Tk()
1230
1231w = Label(root, text="hello good morning")
1232w.pack()
1233
1234b = Button(root, text="click me",command=buttonPushed)
1235b.pack()
1236
1237b1 = Button(root, text="reset me",command=resetPushed)
1238b1.pack()
1239
1240t = Entry()
1241t.pack()
1242
1243root.mainloop()
1244
1245 b. Write a program to access MySQL DB using Python.
1246
1247from tkinter import *
1248import tkinter
1249from tkinter import messagebox
1250from lib2to3.fixer_util import Number
1251import MySQLdb
1252top = tkinter.Tk()
1253L1 = Label(top, text=”First Name”)
1254L1.pack( side = LEFT)
1255E1 = Entry(top, bd =5)
1256E1.pack(side = LEFT)
1257L2 = Label(top, text=”Second Name”)
1258L2.pack( side = LEFT)
1259E2 = Entry(top, bd =5)
1260E2.pack(side = LEFT)
1261”’L3 = Label(top, text=”Answer”)
1262L3.pack( side = LEFT)
1263E3 = Entry(top, bd =5)
1264E3.pack(side = LEFT)”’
1265defbuttonCallBack(selection):
1266print(“E1.get()”+E1.get())
1267print(“E2.get()”+E2.get())
1268print(“selection”+selection)
1269a = E1.get()
1270b = E2.get()
1271if selection in (‘Insert’):
1272# Open database connection
1273db = MySQLdb.connect(“localhost”,”siddhu”,”siddhu”,”siddhutest” )
1274# prepare a cursor object using cursor() method
1275cursor = db.cursor()
1276# execute SQL query
1277cursor.execute(“SELECT VERSION()”)
1278# Fetch a single row
1279data = cursor.fetchone()
1280print (“Database version : %s ” % data)
1281# Drop table if it already exist
1282cursor.execute(“DROP TABLE IF EXISTS SIDDHU_TEST”)
1283# Create table Example
1284sql = “””CREATE TABLE SIDDHU_TEST (
1285FNAME CHAR(20) NOT NULL,
1286LNAME CHAR(20))”””
1287cursor.execute(sql)
1288# 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.
1289sql = “INSERT INTO SIDDHU_TEST(FNAME, \
1290LNAME) \
1291VALUES (‘%s’, ‘%s’)” % \
1292(‘siddhu’, ‘dhumale’)
1293try:
1294# Execute command
1295cursor.execute(sql)
1296# Commit changes
1297db.commit()
1298except:
1299# Rollback if needed
1300db.rollback()
1301# disconnect from server
1302db.close()
1303print(“Data Inserted properly “+a +”–“+b)
1304elif selection in (‘Update’):
1305# Open database connection
1306db = MySQLdb.connect(“localhost”,”siddhu”,”siddhu”,”siddhutest” )
1307# prepare a cursor object using cursor() method
1308cursor = db.cursor()
1309# execute SQL query
1310cursor.execute(“SELECT VERSION()”)
1311# Fetch a single row
1312data = cursor.fetchone()
1313print (“Database version : %s ” % data)
1314# Update Exmaple:- Update record
1315sql = “UPDATE SIDDHU_TEST SET LNAME = ‘%s'” % (b) +” WHERE FNAME = ‘%s'” % (a)
1316try:
1317# Execute the SQL command
1318cursor.execute(sql)
1319# Commit your changes in the database
1320db.commit()
1321except:
1322# Rollback in case there is any error
1323db.rollback()
1324db.close()
1325print(“Data Updated properly “+a +”–“+b)
1326elif selection in (‘Delete’):
1327# Open database connection
1328db = MySQLdb.connect(“localhost”,”siddhu”,”siddhu”,”siddhutest” )
1329# prepare a cursor object using cursor() method
1330cursor = db.cursor()
1331# execute SQL query
1332cursor.execute(“SELECT VERSION()”)
1333# Fetch a single row
1334data = cursor.fetchone()
1335print (“Database version : %s ” % data)
1336# Delete Operation :- Delete Opearations
1337sql = “DELETE FROM SIDDHU_TEST WHERE FNAME = ‘%s'” % (a)
1338try:
1339# Execute the SQL command
1340cursor.execute(sql)
1341# Commit your changes in the database
1342db.commit()
1343except:
1344# Rollback in case there is any error
1345db.rollback()
1346db.close()
1347print(“Data Deleted properly “+a +”–“+b)
1348else:
1349# Open database connection
1350db = MySQLdb.connect(“localhost”,”siddhu”,”siddhu”,”siddhutest” )
1351# prepare a cursor object using cursor() method
1352cursor = db.cursor()
1353# execute SQL query
1354cursor.execute(“SELECT VERSION()”)
1355# Fetch a single row
1356data = cursor.fetchone()
1357print (“Database version : %s ” % data)
1358# Select Query Example :- Selecting data from the table.
1359sql = “SELECT * FROM SIDDHU_TEST \
1360WHERE FNAME = ‘%s'” % (a)
1361try:
1362# Execute the SQL command
1363cursor.execute(sql)
1364lname = “”
1365# Fetch all the rows in a list of lists.
1366results = cursor.fetchall()
1367for row in results:
1368fname = row[0]
1369lname = row[1]
1370# Now print fetched result
1371E2.delete(0,’end’)
1372print (“Value Fetch properly lname=”+lname)
1373E2.insert(0, lname)
1374except:
1375db.close()
1376print (“Value Fetch properly”)
1377BInsert = tkinter.Button(text =’Insert’, command=lambda: buttonCallBack(‘Insert’))
1378BInsert.pack(side = LEFT)
1379BUpdate = tkinter.Button(text =’Update’, command=lambda: buttonCallBack(‘Update’))
1380BUpdate.pack(side = LEFT)
1381BDelete = tkinter.Button(text =’Delete’, command=lambda: buttonCallBack(‘Delete’))
1382BDelete.pack(side = LEFT)
1383BSelect = tkinter.Button(text =’Select’, command=lambda: buttonCallBack(‘Select’))
1384BSelect.pack(side = LEFT)
1385label = Label(top)
1386label.pack()
1387top.mainloop()
1388
1389Output:
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403Experiment 13:
1404 a. Write a JQuery Script to implement hide() and show() effects
1405<!DOCTYPE html>
1406<html>
1407<head>
1408<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
1409<script>
1410$(document).ready(function(){
1411 $("#hide").click(function(){
1412 $("p").hide();
1413 });
1414 $("#show").click(function(){
1415 $("p").show();
1416 });
1417});
1418</script>
1419</head>
1420<body>
1421<p>If you click on the "Hide" button, I will disappear.</p>
1422<button id="hide">Hide</button>
1423<button id="show">Show</button>
1424</body>
1425</html>
1426
1427Output:-
1428
1429Clicking on hide will hide text above button and clicking on show will show the text
1430
1431
1432 b. Write a JQuery Script to apply various sliding effects
1433
1434<!DOCTYPE html>
1435<html>
1436<head>
1437<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
1438<script>
1439$(document).ready(function(){
1440 $("#flip").click(function(){
1441 $("#panel").slideToggle("slow");
1442 });
1443});
1444</script>
1445<style>
1446#panel, #flip {
1447 padding: 5px;
1448 text-align: center;
1449 background-color: #e5eecc;
1450 border: solid 1px #c3c3c3;
1451}
1452#panel {
1453 padding: 50px;
1454 display: none;
1455}
1456</style>
1457</head>
1458<body>
1459<div id="flip">Click to slide the panel down or up</div>
1460<div id="panel">Hello world!</div>
1461</body>
1462</html>
1463Output:-
1464
1465Clicking on panel we get toggle working and division is slide down
1466
1467Experiment 14:
1468 a. Write a JQuery script to animate the given image when ever user clicks on a button.
1469<html>
1470<head>
1471<title>The jQuery Example</title>
1472<script type = "text/javascript"
1473src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
1474</script>
1475
1476<script type = "text/javascript" language = "javascript">
1477 $(document).ready(function() {
1478 $(".clickme").click(function(event){
1479 $(".target").toggle('slow', function(){
1480 $(".log").text('Transition Complete');
1481 });
1482 });
1483 });
1484</script>
1485
1486<style>
1487 .clickme{
1488 margin:10px;
1489 padding:12px;
1490 border:2px solid #666;
1491 width:100px;
1492 height:50px;
1493 }
1494</style>
1495</head>
1496
1497<body>
1498<div class = "content">
1499<div class = "clickme">Click Me</div>
1500<div class = "target">
1501<imgsrc = "./images/jquery.jpg" alt = "jQuery" />
1502</div>
1503<div class = "log"></div>
1504</div>
1505</body>
1506</html>
1507
1508Output:-
1509Output before animate
1510
1511After animate
1512
1513
1514 b. Write a JQuery script to apply various CSS effects
1515
1516<!DOCTYPE html>
1517<html>
1518<head>
1519<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
1520<script>
1521$(document).ready(function(){
1522 $("button").click(function(){
1523 $("p").css({"background-color": "yellow", "font-size": "200%"});
1524 });
1525});
1526</script>
1527</head>
1528<body>
1529
1530<h2>This is a heading</h2>
1531
1532<p style="background-color:#ff0000">This is a paragraph.</p>
1533<p style="background-color:#00ff00">This is a paragraph.</p>
1534<p style="background-color:#0000ff">This is a paragraph.</p>
1535
1536<p>This is a paragraph.</p>
1537
1538<button>Set multiple styles for p</button>
1539
1540</body>
1541</html>
1542Output:-
1543
1544After clicking on button we apply same style to all para by css method
1545
1546
1547
1548
1549
1550Experiment 15:
1551 a. Write a program to apply various filters to transform data.
1552
1553
1554<!DOCTYPE html>
1555<html>
1556<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
1557<body>
1558
1559<div ng-app="myApp" ng-controller="namesCtrl">
1560
1561<p>Type a letter in the input field:</p>
1562
1563<p><input type="text" ng-model="test"></p>
1564
1565<ul>
1566<li ng-repeat="x in names | filter:test">
1567 {{ x }}
1568</li>
1569</ul>
1570
1571</div>
1572
1573<script>
1574angular.module('myApp', []).controller('namesCtrl', function($scope) {
1575 $scope.names = [
1576 'Jani',
1577 'Carl',
1578 'Margareth',
1579 'Hege',
1580 'Joe',
1581 'Gustav',
1582 'Birgit',
1583 'Mary',
1584 'Kai'
1585 ];
1586});
1587</script>
1588<p>The list will only consists of names matching the filter.</p>
1589</body>
1590</html>
1591Output:-
1592Initially before applying filter
1593
1594
1595After applying filter
1596
1597
1598
1599b. Write a program to display data in tables in various forms
1600<html>
1601
1602<head>
1603<title>Angular JS Table</title>
1604<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
1605
1606<style>
1607 table, th , td {
1608 border: 1px solid grey;
1609 border-collapse: collapse;
1610 padding: 5px;
1611 }
1612
1613 table tr:nth-child(odd) {
1614 background-color: #f2f2f2;
1615 }
1616
1617 table tr:nth-child(even) {
1618 background-color: #ffffff;
1619 }
1620</style>
1621
1622</head>
1623<body>
1624<h2>AngularJS Sample Application</h2>
1625<div ng-app = "mainApp" ng-controller = "studentController">
1626
1627<table border = "0">
1628<tr>
1629<td>Enter first name:</td>
1630<td><input type = "text" ng-model = "student.firstName"></td>
1631</tr>
1632
1633<tr>
1634<td>Enter last name: </td>
1635<td>
1636<input type = "text" ng-model = "student.lastName">
1637</td>
1638</tr>
1639
1640<tr>
1641<td>Name: </td>
1642<td>{{student.fullName()}}</td>
1643</tr>
1644
1645<tr>
1646<td>Subject:</td>
1647
1648<td>
1649<table>
1650<tr>
1651<th>Name</th>.
1652<th>Marks</th>
1653</tr>
1654
1655<trng-repeat = "subject in student.subjects">
1656<td>{{ subject.name }}</td>
1657<td>{{ subject.marks }}</td>
1658</tr>
1659
1660</table>
1661</td>
1662
1663</tr>
1664</table>
1665
1666</div>
1667
1668<script>
1669varmainApp = angular.module("mainApp", []);
1670
1671mainApp.controller('studentController', function($scope) {
1672 $scope.student = {
1673firstName: "Mahesh",
1674lastName: "Parashar",
1675 fees:500,
1676
1677 subjects:[
1678 {name:'Physics',marks:70},
1679 {name:'Chemistry',marks:80},
1680 {name:'Math',marks:65},
1681 {name:'English',marks:75},
1682 {name:'Hindi',marks:67}
1683 ],
1684
1685fullName: function() {
1686varstudentObject;
1687studentObject = $scope.student;
1688 return studentObject.firstName + " " + studentObject.lastName;
1689 }
1690 };
1691 });
1692</script>
1693
1694</body>
1695</html>
1696
1697Output:-
1698
1699
1700c. Write a program to apply animations
1701
1702<!DOCTYPE html>
1703<html>
1704<style>
1705div {
1706 transition: all linear 0.5s;
1707 background-color: lightblue;
1708 height: 100px;
1709 width: 100%;
1710 position: relative;
1711 top: 0;
1712 left: 0;
1713}
1714
1715.ng-hide {
1716 height: 0;
1717 width: 0;
1718 background-color: transparent;
1719 top:-200px;
1720 left: 200px;
1721}
1722
1723</style>
1724<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
1725<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-animate.js"></script>
1726
1727<body ng-app="myApp">
1728
1729<h1>Hide the DIV: <input type="checkbox" ng-model="myCheck"></h1>
1730
1731<div ng-hide="myCheck"></div>
1732
1733<script>
1734var app = angular.module('myApp', ['ngAnimate']);
1735</script>
1736
1737</body>
1738</html>
1739
1740
1741Output:-
1742
1743
1744Additional Programs
1745
17461. Write a PHP MySQL Program to demonstrate MySQL prepared statement(insert data)
1747
1748<?php
1749//insert query
1750$link = mysqli_connect('localhost', 'root', 'root', 'srikanth');
1751
1752/* check connection */
1753if (!$link) {
1754printf("Connect failed: %s\n", mysqli_connect_error());
1755 exit();
1756}
1757else
1758 echo "connected successfully";
1759
1760$stmt = mysqli_prepare($link, "INSERT INTO employee VALUES (?, ?, ?, ?)");
1761mysqli_stmt_bind_param($stmt, 'isii', $sno, $name,$sal,$num);
1762
1763$sno = 50;
1764$name = "naveesdfn";
1765$num = 30;
1766$sal = 49000;
1767
1768mysqli_stmt_execute($stmt);
1769
1770printf("%d Row inserted.\n", mysqli_stmt_affected_rows($stmt));
1771
1772/* close statement and connection */
1773mysqli_stmt_close($stmt);
1774
1775mysqli_close($link);
1776?>
1777
1778
1779
1780
1781
1782
1783
1784
17852. Write a PHP MySQL Program to demonstrate MySQL prepared statement(select data)
1786
1787<?php
1788$link = mysqli_connect('localhost', 'root', 'root', 'srikanth');
1789
1790/* check connection */
1791if (!$link) {
1792printf("Connect failed: %s\n", mysqli_connect_error());
1793 exit();
1794}
1795else
1796 echo "connected successfully<br>";
1797
1798$stmt = mysqli_prepare($link, "select * from employee where salary>?");
1799
1800$sal=35000;
1801
1802mysqli_stmt_bind_param($stmt, "i", $sal);
1803
1804mysqli_stmt_execute($stmt);
1805
1806mysqli_stmt_bind_result($stmt, $sno, $name, $salary, $deptno);
1807echomysqli_field_count ($link)."<br>";
1808
1809while (mysqli_stmt_fetch($stmt)) {
1810printf ("%d %s %d %d\n<br>", $sno, $name, $salary, $deptno);
1811 }
1812mysqli_stmt_close($stmt);
1813mysqli_close($link);
1814?>
1815
18163. Write a PHP MySQL Program to demonstrate MySQL mysqli_fetch_array / mysqli_fetch_assoc
1817
1818<?php
1819$servername = "localhost";
1820$username = "root";
1821$password = "root";
1822$dbname = "srikanth";
1823// Create connection
1824$conn = mysqli_connect($servername, $username, $password, $dbname);
1825// Check connection
1826if (!$conn) {
1827die("Connection failed: " . mysqli_connect_error());
1828}
1829else
1830echo "Connected successfully<br>";
1831$query = "SELECT * FROM employee";
1832$result = mysqli_query($conn, $query);
1833//$row = mysqli_fetch_ARRAY($result,MYSQLI_BOTH);
1834while($row = mysqli_fetch_ASSOC($result))
1835{ //print_r($row);
1836printf ("idsg is %s name is (%s) %d %d<br>", $row['id'], $row['name'],$row['salary'], $row['deptno']);
1837} ?>
1838
1839
18404. Write a PHP MySQL Program to demonstrate MySQL mysqli_fetch_all
1841
1842<?php
1843$servername = "localhost";
1844$username = "root";
1845$password = "root";
1846$dbname = "srikanth";
1847
1848// Create connection
1849$conn = mysqli_connect($servername, $username, $password, $dbname);
1850
1851// Check connection
1852if (!$conn) {
1853die("Connection failed: " . mysqli_connect_error());
1854}
1855else
1856echo "Connected successfully<br>";
1857$query = "SELECT * FROM employee";
1858$result = mysqli_query($conn, $query);
1859$row = mysqli_fetch_all($result, MYSQLI_NUM);
1860//print_r($row);
1861printf ("%s (%s) %d %d\n", $row[0][0], $row[0][1],$row[0][2], $row[0][3]);
1862?>
1863
1864
1865
18665. Write a PHP MySQL Program to demonstrate MySQL mysqli_multi_query
1867
1868<?php
1869$servername = "localhost";
1870$username = "root";
1871$password = "root";
1872$dbname = "srikanth";
1873
1874// Create connection
1875$conn = mysqli_connect($servername, $username, $password, $dbname);
1876
1877// Check connection
1878if (!$conn) {
1879die("Connection failed: " . mysqli_connect_error());
1880}
1881else
1882echo "Connected successfully<br>";
1883// now as the db connection is done we may perform the required db operation
1884$query = "SELECT user,host from mysql.user;";
1885$query .= "SELECT id,name FROM employee ORDER BY ID desc limit 5,2";
1886
1887/* execute multi query */
1888if (mysqli_multi_query($conn, $query)) {
1889 do {
1890 /* store first result set , returns a mysqli_result*/
1891 $result = mysqli_store_result($conn);
1892
1893 if ($result!=FALSE) {
1894 //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)
1895 while ($row = mysqli_fetch_row($result)) {
1896printf("%s %s<br>", $row[0], $row[1]);
1897 }
1898mysqli_free_result($result);
1899 }
1900printf("<br>-----------------<br>");
1901 /*
1902mysqli_more_results($conn) checks if there are any more query results from a multi query
1903Returns TRUE if one or more result sets are available from a previous call to mysqli_multi_query(), otherwise FALSE*/
1904
1905/*
1906mysqli_next_result Prepares next result from multi_query
1907Returns TRUE on success or FALSE on failure. */
1908 } while (mysqli_more_results($conn) &&mysqli_next_result($conn));
1909}
1910
1911/* close connection */
1912mysqli_close($conn);
1913
1914?>