Apoorva Mehetre
Apoorva Mehetre
Lab
Journal Of
"Python Programming
&
“Advance Internet Technologies"
By
Apoorva Mehetre
Submitted in partial fulfillment of First
Year Master in Computer Application
Savitribai Phule Pune University
Of
1
NAVIGATE TO :
1. PYTHON PRACTICALS
2. AIT PRACTICALS
2
INDEX1
PYTHON PROGRAMMING
SR. NO. TITLE PAGE NO.
1 Python installation and configuration with windows and 4
Linux.
2 Programs for understanding the data types, control flow 6
statements, blocks and loops.
3 Programs for understanding functions, use of built-in 10
functions, user defined functions
4 Programs to use existing modules, packages and 11
creating modules, packages
5 Programs for implementations of all object-oriented 12
concepts like class, method, inheritance, polymorphism etc.
(Real life examples must be covered for the implementation
of object oriented concepts)
6 Programs for parsing of data, validations like 15
Password, email, URL, etc.
7 Programs for Pattern finding should be covered. 18
8 Programs covering all the aspects of Exception handling, 19
user defined exception, Multithreading should be covered.
3
1. Python installation and configuration with windows and Linux.
How to install Python in Windows?
Python is the most popular and versatile language in the current scenario. Python doesn't
come with pre-package in Windows, but it doesn't mean that Window user cannot be flexible
with Python. Some operating systems such as Linux come with the Python package manager
that can run to install Python. Below are the steps to install Python in Windows.
o All Python-related information is available on its official website. First, open the
browser and visit the official site (www.python.org) to install Python installer. Here,
we can see the many Python installer versions, but we will download the latest version
of Python.
o It will take us on the above page. We can download the latest Python installer by
clicking on the Download button. We can also download the older version. Let's see
the following example.
4
Note - You can choose the Python installer according to your processor. If your system
processor has 32-bit, then download Python 32-bit installer, otherwise go with the 64-bit
version. If you are not sure about your processor, then download the 64-bit version.
o Once the download is completed, then run the installer by double-clicking on the
download file. It will ask for Add Python 3.8 to PATH. Click on the checkbox and
click on Install Now navigator.
Now Python is successfully installed in Windows, and you are ready to work with
Python.
(home)
5
2. Programs for understanding the data types, control flow statements, blocks and
loops.
CODE:
#PYTHON_DATA_TYPES
#1.Python_numbers a
=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
#2.List
a = [5,10,15,20,25,30,35,40]
a[2] = 15
print("a[2] = ", a[2])
#3.Tuple
t = (5,'program', 1+3j)
#t[1] = 'program'
#print("t[1] = ", t[1])
#4.Set
a = {5,2,3,1,4}
a = {1,2,2,3,3,3}
print(a)
#5.Dictionary
d = {1:'value','key':2}
print(type(d))
6
print("d['key'] = ", d['key'])
#string
s = "This is a string"
print(s)
s = '''A multiline
string'''
print(s)
print("\n")
#1.if condition
# If the number is positive, we print an appropriate message
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1 if
num > 0:
print(num, "is a positive number.")
print("This is also always printed.")
num = 3.4
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
#4.nested if condition
'''In this program, we input a number
check if the number is positive or
negative or zero and display
an appropriate message
This time we use nested if statement'''
7
else:
print("Positive number")
else:
print("Negative number")
#Loops
#1.while loop
secret_number = 777
print(
"""
+================================+
| Welcome to my game, muggle! |
| Enter an integer number |
| and guess what number I've |
| picked for you. |
| So, what is the secret number? |
+================================+
""")
#2.for loop
for second in range(1, 6):
print(second, "Mississippi")
print("Ready or not, here I come!")
if counter:
print("The largest number is", largest_number)
else:
print("You haven't entered any number.")
8
OUTPUT:
(home)
9
3. Programs for understanding functions, use of built-in functions, user defined
functions.
CODE:
#example of built-in functions
x = zip(a, b)
print(x)
x = type(a1)
y = type(b2)
z = type(c3)
print(x, y, z)
def sum(a,b):
total = a + b
return total
x = 10
y = 20
#example2
def is_a_triangle(a, b, c): if
a + b <= c:
return False
if b + c <= a:
return False
if c + a <= b:
return False
return True
10
print(is_a_triangle(1, 1, 1))
print(is_a_triangle(1, 1, 3))
OUTPUT:
(home)
CODE:
# importing sqrt() and factorial from the
# module math
# are required.
print(sqrt(16))
print(factorial(6))
D:\Python\Learn\venv\Scripts\python.exe D:/Python/Learn/main.py
4.0
720
import random
# printing random integer between 0 and 5
11
print(random.randint(0, 5))
print(random.random())
print(random.random() * 100)
List = [1, 4, True, 800, "python", 27, "hello"]
# using choice function in random module for choosing
# a random element from a set such as a list
print(random.choice(List))
D:\Python\Learn\venv\Scripts\python.exe D:/Python/Learn/main.py
OUTPUT:
1
0.9203095513570789
94.43468017867225
800
(home)
CODE:
#Creating Class and Object in Python
class Parrot:
# class attribute
species = "bird"
# instance attribute
def init (self, name, age):
self.name = name
self.age = age
12
blu = Parrot("Blu", 10)
woo = Parrot("Woo", 15)
# instance attributes
def init (self, name, age): self.name =
name
self.age = age
def dance(self):
return "{} is now dancing".format(self.name)
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
# child class
class Penguin(Bird):
def whoisThis(self):
print("Penguin")
def run(self):
13
print("Run faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()
# instantiate objects
blu = Parrot()
peggy = Penguin()
OUTPUT:
14
(home)
6. Programs for parsing of data, validations like Password, email, URL, etc.
CODE:
# Python program to validate an Email
# import re module
def check(email):
else:
print("Invalid Email")
# Driver Code
if name == ' main ':
15
email = "[email protected]"
email = "[email protected]"
check(email)
email = "ankitrai326.com"
check(email)
if len(passwd) < 6:
print('length should be at least 6')
val = False
# Main method
def main():
passwd = 'Geek12@'
if (password_check(passwd)):
print("Password is valid")
else:
print("Invalid Password !!")
# Driver Code
if name == ' main ':
main()
16
#Parsing and Processing URL using Python
# import library
import re
# url link
s = 'file://localhost:4040/abc_file'
OUTPUT:
(home)
17
7. Programs for Pattern finding should be covered.
CODE:
import re
phoneValid = False
def phoneValidation():
else:
global phoneValid
phoneValid=True
return
phoneValidation()
OUTPUT:
D:\Python\Learn\venv\Scripts\python.exe D:/Python/Learn/main.py
Enter Phone: 27412159
Please enter a valid phone number with code
Enter Phone: 02027412159
Phone validated successfully. Good job!
CODE:
import re
def validating_name(name):
if regex_name.search(name):
print(f'{name} is valid')
18
else:
print(f'{name} is invalid')
OUTPUT:
D:\Python\Learn\venv\Scripts\python.exe D:/Python/Learn/main.py
Mr. Albus Severus Potter is valid
Lily and Mr. Harry Potter is invalid
(home)
CODE:
import re
class InvalidName(RuntimeError):
self.args = arg
def validating_name(name):
try:
if regex_name.search(name):
print(f'{name} is valid')
else:
raise InvalidName(name)
except InvalidName as e:
19
validating_name('Lily and Mr. Harry Potter')
D:\Python\Learn\venv\Scripts\python.exe D:/Python/Learn/main.py
Mr. Albus Severus Potter is valid
Error: Lily and Mr. Harry Potter is invalid
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
OUTPUT:
D:\Python\Learn\venv\Scripts\python.exe D:/Python/Learn/main.py
Enter a:10
Enter b:0
Error : Can't divide with zero
(home)
9. Programs demonstrating the IO operations like reading from file, writing into file
from different file types like data file, binary file, etc.
CODE:
#Open and closeing file in python
try:
f = open("Dev.txt", "r")
finally:
f.close()
content = f.read()
print(content)
20
f.read(4) # read the next 4 data
' is '
(home)
10. Programs to perform searching, adding, updating the content from the file.
CODE:
#adding
import pickle
list =[]
while True:
roll = input("Enter student Roll No:")
sname = input("Enter student Name :")
student = {"roll":roll,"name":sname}
list.append(student)
choice= input("Want to add more record(y/n) :")
if(choice=='n'):
break
file = open("E:\student.dat","wb")
pickle.dump(list,file)
file.close()
#Searching:
import pickle
name = input('Enter name that you want to search in binary file :')
found = 0
21
for x in list:
if name in x['name']:
found = 1
print("Found in binary file" if found == 1 else "Not found")
#Update:
import pickle
name = input('Enter name that you want to update in binary file :')
found = 0
lst = []
for x in list:
if name in x['name']:
found = 1
x['name'] = input('Enter new name ')
lst.append(x)
if(found == 1):
file.seek(0)
pickle.dump(lst, file)
print("Record Updated")
else:
print('Name does not exist')
file.close()
OUTPUT:
(home)
22
11. Program for performing CRUD operation with MongoDB and Python.
CODE:
from pymongo import MongoClient
# Creating a collection
coll = db['Del']
"mark": "71%"
},
{
"_id": "7",
"name": "seema",
"dept": "KCN",
"mark": "40%"
23
},
{
"_id": "8",
"name": "ajit",
"dept": "MCA",
"mark": "59%"
}
]
res = coll.insert_many(data)
print("Data inserted ")
myquery = {"_id": {"$lte": "2"}}
x = coll.delete_many(myquery)
print(x.deleted_count, " documents deleted.")
OUTPUT:
24
(home)
12. Basic programs with NumPy as Array, Searching and Sorting, date & time and
String handling.
CODE:
# Python program for
# Creation of Arrays
import numpy as np
25
arr = np.array((1, 3, 2))
print("\nArray created using " "passed tuple:\n", arr)
#Searching
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
arr = ['t','u','t','o','r','i','a','l']
x = 'a'
#Sorting
arr[i] = arr[j];
arr[j] = temp;
print();
26
#String handling
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
OUTPUT:
27
28
(home)
29
13. Programs for series and data frames should be covered.
CODE:
#series
import pandas as pd
d1 = {'a': 100, 'b': 200, 'c':300, 'd':400, 'e':800}
print("Original dictionary:")
print(d1)
new_series = pd.Series(d1)
print("Converted series:")
print(new_series)
#data frames
import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura',
'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels)
print(df)
OUTPUT:
30
(home)
14. Programs to demonstrate data pre-processing and data handling with data frame
CODE:
# Importing pandas
import pandas as pd
# Importing training data set
X_train=pd.read_csv('X_train.csv')
Y_train=pd.read_csv('Y_train.csv')
31
OUTPUT:
(home)
CODE:
# import pandas and matplotlib
import pandas as pd
import matplotlib.pyplot as plt
32
['E006', 'M', 36, 121, 'Normal', 80],
'Age', 'Sales',
'BMI', 'Income'] )
# show plot
plt.show()
OUTPUT:
(home)
33
INDEX2
34
1. Program to implement Audio and Video features for your web page.
CODE:
<!Doctype>
<Html>
<body>
<h1> The video element </h1>
<video width="390" height="400" controls>
<source src="elephant.mp4" type="video/mp4">
<source src="elephant.ogg" type="video/mp4">
</video>
OUTPUT:
(home)
35
2. Program to design form using HTML5 elements, attributes and Semantics.
CODE:
<html>
<body>
<form action="/signup" method="post">
<p>
<h3><label>Sign up form:</label></h3><br><br>
<label>
<input type="radio" name="title" value="mr">
Mr
</label>
<label>
<input type="radio" name="title" value="mrs">
Mrs
</label>
<label>
<input type="radio" name="title" value="miss">
Miss
</label>
</p>
<p>
<label>First name</label><br>
<input type="text" name="first_name">
</p>
<p>
<label>Last name</label><br>
<input type="text" name="last_name">
</p>
<p>
<label>Email</label><br>
<input type="email" name="email" required>
</p>
<p>
<label>Phone number</label><br>
<input type="tel" name="phone" placeholder="123-45-678" pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}"
requierd>
</p>
<p>
<label>Password</label><br>
<input type="password" name="password">
</p>
<p>
<label for="date">
<span>Birth date:</span>
<strong>
<abbr title="required">*</abbr>
</strong>
</label>
36
<label>Country</label><br>
<select>
<option>India</option>
<option>Australia</option>
<option>United States</option>
<option>Indonesia</option>
<option>Brazil</option>
</select>
</p>
<p>
<br>
<label>
<input type="checkbox" value="terms">
I agree to the <a href="/terms">terms and conditions</a>
</label>
</p>
<p>
<button>Sign up</button>
<button type="reset">Reset form</button>
</p>
</form>
</body>
</html>
OUTPUT:
(home)
37
3. Programs using Canvas and SVG.
CODE:
<!DOCTYPE html>
<html>
<body>
<p>This is example of HTML Canvas Graphics </p>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create gradient
var grd = ctx.createRadialGradient(75,50,5,90,60,100);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p>
This is example of SVG Graphics
</p>
<svg height="130" width="500">
<defs>
<linearGradient id="grad1" x1="0%" y1="20%" x2="100%" y2="0%">
<stop offset="10%"
style="stop-color:rgb(255,105,180);stop-opacity:1" />
<stop offset="90%"
style="stop-color:rgb(139,0,139);stop-opacity:1" />
</linearGradient>
</defs>
<ellipse cx="100" cy="70" rx="85" ry="55" fill="url(#grad1)" />
<text fill="#ffffff" font-size="45" font-family="Verdana"
x="50" y="86">Dev</text>
Sorry, your browser does not support inline SVG.
</svg>
</body>
</html>
38
OUTPUT:
(home)
39
4. Programs to demonstrate external and internal styles in the web page using font,
text, background, borders, opacity and other CSS 3 properties.
CODE:
Internal CSS:-
<html>
<head>
<style>
img {
opacity: 0.5;;
}
body {
background-color:#FFBF00;
}
h1 {
font-family: "Lucida Handwriting",monospace;
color: red(245, 241, 245);
padding: 50px;
}
h3{
font-family: "Lucida Console", "Courier New", monospace;
color:red(3, 7, 7);
}
</style>
</head>
<body>
<div class="background">
<h1>Internal CSS</h1>
<p><h3>Cascading Style sheet types: inline, external and internal</h3></p>
</div>
<p>Image with 50% opacity:</p>
<img src="forest.JFIF" alt="loading" width="320" height="250">
</body>
</html>
<html>
<head>
<link rel="stylesheet" href="External CSS.css">
</head>
<body>
<h1>External CSS </h1>
<p><p><h3>Cascading Style sheet types: inline, external and internal</h3></p>
</p>
<p>Image with 50% opacity:</p>
<img src="waterfall.JFIF" alt="Palace" width="320" height="250">
<img src="nature.JFIF" alt="Bell" width="320" height="250">
<img src="fort.JFIF" alt="Lizard" width="320" height="250">
</body>
</html>
40
OUTPUT:
(home)
41
5. Implement Transformation using Translation, Rotation and Scaling in your web
page.
CODE:
<html>
<head>
<p>Dev</p><br><br><br>
<style>
div {
width: 190px;
height: 20px;
text-align: center;
background-color: pink;
}
.rotate1 {
/* specify rotation properties for class rotate1 */
transform: rotate(20deg);
background-color: skyblue;
}
.rotate2 {
/* specify rotation properties for class rotate2 */
transform: rotate(50deg);
background-color: red;
}
</style>
</head>
<body>
OUTPUT:
42
(home)
6. Program to show current date and time using user defined module.
CODE:
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
OUTPUT:
Current date and time:
2021-10-14 19:54:16
(home)
7. Program using built-in modules to split the query string into readable parts.
CODE:
const querystring = require('querystring');
const url = "http://example.com/index.html?code=string&key=12&id=false";
const qs = "code=string&key=12&id=false";
console.log(querystring.parse(qs));
// > { code: 'string', key: '12', id: 'false' }
console.log(querystring.parse(url));
OUTPUT:
(home)
43
8. Program using NPM which will convert entered string into either case.
CODE:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
string = fruits.join(' ').toUpperCase();
console.log("convert the string lowercase to uppercase",string)
OUTPUT:
(home)
9. Write a program to create a calculator using Node JS. (Install and configure Node
JS and Server)
CODE:
//Hapi framework
import { Server } from 'hapi';
//Create server
const server = Server({
host: host,
port: port
});
//Routes
require('./routes')(server);
//Start server
const init = async () => {
await server.start();
console.log("Server up! Port: " + port);
}
//Start App
init();
export default function (server) {
44
//route - about
server.route({
method: 'GET',
path: '/calculadora/about',
handler: function (request, h) {
var data = {
message: 'Calculator API - made by Bernardo Rocha'
};
return data;
}
});
//route - sum
server.route({
method: 'GET',
path: '/calculator/sum/{num1}+{num2}',
handler: function (request, h) {
var data = {
answer: num1 + num2
};
return data;
}
});
//route - subtraction
server.route({
method: 'GET',
path: '/calculator/sub/{num1}-{num2}',
handler: function (request, h) {
var data = {
answer: num1 - num2
};
return data;
}
45
});
//route - multiplication
server.route({
method: 'GET',
path: '/calculator/multi/{num1}*{num2}',
handler: function (request, h) {
var data = {
answer: num1 * num2
};
return data;
}
});
//route - division
server.route({
method: 'GET',
path: '/calculator/div/{num1}/{num2}',
handler: function (request, h) {
return data;
}
});
}
OUTPUT:
(home)
46
10. Write Program for Form validation in Angular.
CODE:
import { Component, OnInit } from '@angular/core';
//import validator and FormBuilder
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
}
}
<div>
<h2>
Required Field validation
</h2>
<form[formGroup]="requiredForm" novalidate>
<div class="form-group">
<label class="center-block">Name:
<input class="form-control" formControlName="name">
</label>
</div>
<div *ngIf="requiredForm.controls['name'].invalid && requiredForm.controls['name'].touched "
class="alert alert-danger">
<div *ngIf="requiredForm.controls['name'].errors.required">
Name is required.
</div>
</div>
</form>
<p>Form value: {{ requiredForm.value | json }}</p>
<p>Form status: {{ requiredForm.status | json }}</p>
47
</div>
OUTPUT:
(home)
CODE:
:- import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-server2',
templateUrl: './server2.component.html',
styleUrls: ['./server2.component.css']
})
export class Server2Component implements OnInit { allowNewServer = false;
serverCreationStatus = 'No server is created.';
serverName = 'TestServer';
serverCreated = false;
/*constructor() { setTimeout(() =>{ this.allowNewServer = true;
Submit
}, 5000);
}*/
ngOnInit() {
}
onCreateServer() { this.serverCreated = true;
this.serverCreationStatus = 'Server is created. Name of the server is' + this.serverName;
}
OnUpdateServerName(event: Event) {
this.serverName = (<HTMLInputElement>event.target).value;
}
ngif
48
@Component({
selector: 'ngif-example',
template: `
<h4>NgIf</h4>
<ul *ngFor="let person of people">
<li *ngIf="person.age < 30"> (1)
{{ person.name }} ({{ person.age }})
</li>
</ul>
`
})
class NgIfExampleComponent {
people: any[] = [
{
"name": "Douglas Pace", "age":
35
},
{
"name": "Mcleod Mueller",
"age": 32
},
{
"name": "Day Meyers",
"age": 21
},
{
"name": "Aguirre Ellis",
"age": 34
},
{
"name": "Cook Tyson",
"age": 32
}
];
}
Ngswitch:
49
</li>
<li *ngIf="person.country !== 'HK' && person.country !== 'UK' && person.country !== 'USA'"
class="text-warning">{{ person.name }} ({{ person.country }})
</li>
</ul>
.html
@Component({
selector: 'ngswitch-example',
template: `<h4>NgSwitch</h4>
<ul *ngFor="let person of people"
[ngSwitch]="person.country"> (1)
people: any[] = [
{
"name": "Douglas Pace", "age":
35,
"country": 'MARS'
},
{
"name": "Mcleod Mueller",
"age": 32,
"country": 'USA'
},
{
"name": "Day Meyers",
"age": 21,
"country": 'HK'
},
{
"name": "Aguirre Ellis",
"age": 34,
50
"country": 'UK'
},
{
"name": "Cook Tyson",
"age": 32,
"country": 'USA'
}
];
}
OUTPUT:
51
(home)
12. Create angular project which will demonstrate the usage of component
directive, structural directive and attribute directives.
CODE:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
@NgModule({
declarations: [
AppComponent,
ChangeColorDirective // Custom directive is declared in declartions array by Angular CLI
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
52
// Custom directive imported here by Angular CLI
import { ChangeColorDirective } from './change-color.directive';
@NgModule({
declarations: [
AppComponent,
ChangeColorDirective // Custom directive is declared in declartions array by Angular CLI
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
change-color.directive.ts
import { Directive } from '@angular/core';
@Directive({
selector: '[appChangeColor]'
})
constructor() { }
App.component.html
<div style="text-align:center">
OUTPUT:
53
(home)
13. Create angular project which has HTML template and handle the click event
on click of the button (Installation of Angular and Bootstrap 4 CSS
Framework).
CODE:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Angular Bootstrap Demo</title>
<base href="/">
54
<div class="container">
<div class="jumbotron">
<h1>Welcome</h1>
<h2>Angular & Bootstrap Demo</h2>
</div>
OUTPUT:
(home)
14. Program for basic operations, array and user interface handling.
CODE:
Array.php
<?php
class myclass implements ArrayAccess {
private $arr = array();
public function construct() {
$this->arr = array("Mumbai", "Hyderabad", "Patna");
}
public function offsetSet($offset, $value) {
if (is_null($offset)) {
$this->arr[] = $value;
} else {
$this->arr[$offset] = $value;
}
55
}
public function offsetExists($offset) {
eturn isset($this->arr[$offset]);
}
public function offsetUnset($offset) {
unset($this->arr[$offset]);
}
public function offsetGet($offset) {
return isset($this->arr[$offset]) ? $this->arr[$offset] : null;
}
}
$obj = new myclass();
var_dump(isset($obj[0]));
var_dump($obj[0]);
unset($obj[0]);
var_dump(isset($obj[0]));
$obj[3] = "Pune";
var_dump($obj[3]);
$obj[4] = 'Chennai';
$obj[] = 'NewDelhi';
$obj[2] = 'Benguluru';
print_r($obj);
?>
OUTPUT:
(home)
56
15. Program to demonstrate session management using various techniques.
CODE:
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
OUTPUT:
(home)
57
16. Program to perform the CRUD Operations using PHP Script.
CODE:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Print host information
echo "Connect Successfully. Host info: " . mysqli_get_host_info($link);
?>
OUTPUT:
CODE:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt create database query execution
$sql = "CREATE DATABASE demo";
if(mysqli_query($link, $sql)){
echo "Database created successfully";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
58
OUTPUT:
CODE:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
OUTPUT:
59
CODE:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES ('Yograj', 'Shirsath', 'yogr
[email protected]')";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
60
OUTPUT:
CODE:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt update query execution
$sql = "UPDATE persons SET email='[email protected]' WHERE id=1";
if(mysqli_query($link, $sql)){
echo "Records were updated successfully.";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
OUTPUT:
61
CODE:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Close connection
mysqli_close($link);
?>
OUTPUT:
62
(home)
63
64