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