WE Lab

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

RAMESH KUMAR TCT-002

Workbook Web Engineering (CT – 362)

Name RAMESH KHATRI


Roll No TCT-002
Batch 2019
Year Third Year
Departmen BCIT
t

Prepared by Mrs. Nazish Irfan I.T Manager,


Department of Computer Science and Information
Technology
Approved by
Chairman
Department of Computer
Science and Information
Technology
Department of Computer Science and Information Technology

CT-362: Web Engineering Page 1


RAMESH KUMAR TCT-002

Table of Contents

S. No Object Page No Signatures

1. Introduction to HTML. 04

2. Exploring Basic HTML Elements. 07

3. Introduction to HTML5. 18

4. Exploring HTML5 Elements. 21

5. Introduction to Cascading Style Sheets. 29

6. Introduction to Javascript. 41

7. Introduction to ASP.NET. 60

Exploring some controls and the concept of field


8. 64
validation in ASP.NET.

Exploring the working of Login controls and some


9. 67
basic Postback controls in ASP.Net.

10. Working with Databases in ASP.Net 69

11 Introduction to PHP 72

12 PHP Variables, Control Structures and Loops 74

13 MySQL and PHP 81

14 Select, Insert, Update and Delete in PHP/MYSQL 84

Note: The following software is used: Sublime/Dreamweaver/Notepad,


Browser IE, Chrome and Opera, XAMPP/WAMP.

Lab # 1

CT-362: Web Engineering Page 2


RAMESH KUMAR TCT-002

Exercise:
1. Which of the following is a properly formed HTML document?
A. <html>
<head>
<title>My document</title>
<body>This is my web page</body>
</title>
</html>

B. <HTML>
<HEAD>
<TITLE>My document</TITLE>
<BODY>This is my web page
</HTML>

C. <html>
<head><title>My document</title></head>
<body>This is my web page</body>
</html>

D. <HTML>
<HEAD>
<TITLE>My document</HEAD>
<BODY>This is my web page</BODY>
</HTML>

ANSWER::::
C is correct:

<html>
<head>
  <title>My document</title>
</head>
<body>
This is my page
</body>
</html>

2. What are the advantages and disadvantages of


HTML.

CT-362: Web Engineering Page 3


RAMESH KUMAR TCT-002

Advantages: 
 
 HTML helps to build structure of a website and is a widely used
Markup language.
 It is easy to learn.
 Every browser supports HTML Language.
 HTML is light weighted and fast to load.
 Storage of big files are allowed because of the application cache
feature.
 Do not get to purchase any extra software because it’s by default in
every window.
 Loose syntax (although, being too flexible won’t suit standards).
 HTML is simple to edit as being a plain text.
 It integrates easily with other languages such as JavaScript, CSS etc.
 HTML is that it is easy to code even for novice programmers.
 HTML also allows the utilization of templates, which makes designing
a webpage easy.

Disadvantages : 
 
 It cannot produce dynamic output alone, since it’s a static language.
 Making the structure of HTML documents becomes tough to
understand.
 Errors can be costly.
 It is the time consuming as the time it consume to maintain on the
color scheme of a page and to make lists, tables and forms.
 We need to write a lot of code for just creating a simple webpage.
 We have to check up the deprecated tags and confirm not to use them
to appear because another language that works with HTML has
replaced the first work of the tag, and hence the opposite language
needs to be understood and learned.
 Security features offered by HTML are limited.
 If we need to write down long code for creating a webpage then it
produces some complexity.
 HTML can create only static and plain pages so if we’d like dynamic
pages then HTML isn’t useful.
 Editing of web page need to be done separately, they are not
centralized.

Lab # 2
Exercise:

CT-362: Web Engineering Page 4


RAMESH KUMAR TCT-002

a. A paragraph that is a description of a book, include the title of the book as


well as its author. Names and titles should be underlined, italicized and
bolded.
Code:

OUTPUT:

b. Print two lists with any information you want. One list should be an ordered
list and the other should be unordered list.

CODE:

CT-362: Web Engineering Page 5


RAMESH KUMAR TCT-002

OUTPUT:

c. Create a page with a link at the top of it when clicked will jump all the way to the
bottom of the page and at the bottom of the page there should be a link to jump
back to the top of the page.

Code: Output:

CT-362: Web Engineering Page 6


RAMESH KUMAR TCT-002

d. Create some links to various search engines.

Code:

Output:(here I will click frist link)

CT-362: Web Engineering Page 7


RAMESH KUMAR TCT-002

e. Display an image that when clicked will link to a search engine of


your choice and the page should open in a new window.

CODE: OUTPUT

F).Design a form to take input from the user to generate his / her CV.
CODE:

CT-362: Web Engineering Page 8


RAMESH KUMAR TCT-002

OUTPUT:

Lab # 3
Exercise:

1-Write down the advantages and disadvantages of HTML5.

CT-362: Web Engineering Page 9


RAMESH KUMAR TCT-002

Advantages of HTML5
1) HTML5 helps you embed video & audio , high-quality drawings , the charts , the
animation and many other types of rich content without using any plugins or third
party programs as the functionality is now built into the browser and you can
access HTML5 apps without downloading them to your phones .

2) HTML5 offers more descriptive & improved semantics , It has richer media
elements , You can use cleaner , neater code , You can remove most div tags &
replace them with the semantic HTML 5 elements , You can increase the semantic
value of the web page because the codes are very standardized by using HTML5
elements .

3) You will see more greater consistency in terms of the HTML used to code the web
page on one site compared to another because the websites adopt the new HTML5
elements , This will make it more easier for the designers & the developers to
understand how the web page is structured .

4) New features & standards have emerged as part of HTML5 , Once you detect the
available features in today’s browsers , you can take advantage of those features in
your application , You can make easier application with easy front-ends , drag &
drop tools , discussion boards , wikis & the other useful elements .

5) With HTML 5 , While building the site , You can specify the files that the browser
should cache , So , if you refresh the page when you are offline , the page will load
correctly , This kind of caching has many advantages like offline browsing , files
load much faster & reduced load on the server .

6) The cookies are used to track unique user data for years but they have serious
disadvantages , The largest flaw is that all of your cookies data are added to every
HTTP request header , This can end up having the measurable impact on response
time , So , The best practice is to reduce cookies size .

7) With HTML5 , we can do better by using session Storage & local Storage ( two
different storage in HTML5 ) in the place of cookies , It is not the permanent
database , but it enables you to store structured data temporarily .

CT-362: Web Engineering Page 10


RAMESH KUMAR TCT-002

Disadvantages of HTML5
1) HTML5 is not being used widely , So , It would not be accessible by all systems ,
Only modern browsers support it , The parts of the language are very stable but
HTML 5 is considered a work in progress , so technically , any of the elements
could change at any time .

2) HTML5 lacks the monetization power which the Apple & Google app stores
provide , The users do not have the central location from which they can look
through & purchase HTML5 apps , Instead many of these apps have to rely on the
money from advertising .

3) It is simply not as lucrative , Due to limited access to many mobile phone’s


features & varied support of HTML5 across the browsers , The developers have to
rely on the workarounds to get the functionality they need .

4) When the change or the feature is added in iOS , Android or Windows , HTML5
development tool should reflect or take into account the change & make the
necessary adjustments in the code , So , The tools of mobile application
development platform go behind the official SDK .

5) It takes too much time to get the mobile applications ready because the developers
have to write the code for each platform , The difference in the execution times of
the platforms causes the complications in the mobile application development
platform .

6) The developers work in the languages that are not native to the platforms , so , The
efficiency of the code depends on the translation engine , It happens that coding
techniques are inefficient or the code is redundant .

7) HTML5 standard was evolved in a short period & this produced the discrepancies
in the implementation of CSS attributes , HTML tags and JavaScript APIs , these
features behave differently on different platforms , although there are tools
available to resolve these discrepancies .

8) There is ugly fact about HTML5 which is Media Licensing Issues , It can not
produce dynamic output , The security elements offered by HTML5 is limited ,
HTML5 supports modern browsers except for the internet explorer , Older
browsers ( such as IE8 & below ) will need JavaScript-based poly-fills & basic
CSS to make the elements behave as intended .

9) The primary drawback with HTML5’s acknowledgment is that cutting edge


programs bolster it, HTML5 is an evolving standard, So, Any of its more
advanced features could be tweaked or changed during the process of its
development.

Lab # 4

CT-362: Web Engineering Page 11


RAMESH KUMAR TCT-002

1. Create the form shown in the figure below.


Exercise:
1. Create the form shown in the figure below

Code: Output;
<form>
<h2 style="color:rgb(23, 23, 134)">A Simple Form</h2>
<h4 style="color:rgb(124, 124, 124)"><i>Form
Fundamentals</i></h4>
<fieldset>
<legend>Customer Info:</legend><br/>
<label>Name<input type="text" placeholder="Enter your
Name" autofocus="autofocus"
required="required" /></label><br /><br />
<label>Telephone<input type="text" placeholder="1-234-567-
8910" required="required" /><br /><br /></label>
<label>Email Address<input type="text" placeholder="Enter
your Email Address" required="required" /></label>
</fieldset>
<fieldset><br/>
<legend>Books</legend>
<select>
<option value="0">Select A Book</option>
<option value="1">Twilight</option>
<option value="2">Gone Girl</option>
<option value="3">Veronika Decides to Die</option>
<option value="4">Alchemist</option>
<option value="5">Angels and Demons</option>
</select>
<label>Quantity(Maximum 5) <input type="number"
max="5" min="1" /></label>
</fieldset>
</form>

Lab # 5

CT-362: Web Engineering Page 12


RAMESH KUMAR TCT-002

Exercise:
1. What are the advantages and disadvantages of CSS.

Advantages
 CSS saves a lot of time.
 It helps to make consistent and spontaneous changes.
 It improves the loading speed of the page.
 CSS has the ability to re-position.
 It has better device compatibility.
 It is less complex therefore the effort are significantly reduced.
 It helps to form spontaneous and consistent changes.
 CSS changes are device friendly. With people employing a batch of various range
of smart devices to access websites over the web, there’s a requirement for
responsive web design.
 It has the power for re-positioning. It helps us to determine the changes within the
position of web elements who are there on the page.

Disadvantages
 There could be cross-browser issues while using CSS.
 There are multiple levels of CSS such as CSS, CSS 2, CSS 3. This can create
confusion for non-developers and beginners.
 With CSS, what works with one browser might not always work with
another. The web developers need to test for compatibility, running
the program across multiple browsers.
 There exists a scarcity of security.
 After making the changes we need to confirm the compatibility if
they appear. The similar change affects on all the browsers.
 The programing language world is complicated for non-developers
and beginners. Different levels of CSS i.e. CSS, CSS 2, CSS 3 are
often quite confusing.
 Browser compatibility (some styles sheet are supported and some
are not).
 CSS works differently on different browsers. IE and Opera supports
CSS as different logic.
 There might be cross-browser issues while using CSS.
 There are multiple levels which creates confusion for non-
developers and beginners.

2. What is the advantage of CSS web design over tables.

CT-362: Web Engineering Page 13


RAMESH KUMAR TCT-002

 Web pages will load faster


No one likes waiting for web pages to load and if a page takes too long to load,
many users will often simply leave. Generally, CSS based page layouts require
much less html coding than table-based layouts. This usually results in the pages
loading more quickly. Moreover, an externally linked CSS file, once loaded the first
time, does not have to be reloaded and re-read on every page. When using CSS
for layout, browsers can cache (keep in memory) all the formatting and stylizing
for your pages instead of having to read and interpret each style tag on every
page. This can also result in much faster page loading times!
 Visual consistency across pages
One of the strengths of using Cascading Style Sheets in a website layout is that
design elements can be defined in a single place (the css file) and will
automatically be applied to those elements on the website. No longer does each
individual page have to be updated to reflect the new style. This makes for much
greater consistency throughout the site. With CSS, you do not have to re-code
every element on every page (and check and double check that you didn't miss
some pages!), styling updates are automatic and site-wide.
 Accessibility and usability
CSS allows for more interactive style elements, including font size and line
heights, which can make web pages more usable for people with disabilities. Web
pages that use CSS layouts are also often more compatible with more browsers.
What's more, designers can create specific css files specifically for printing, or
mobile devices, as well as the standard computer screen, thereby making
websites truly multimedia applications.
 CSS is better for SEO
Since pages load faster with CSS Layouts, search engines can more easily crawl
through the site. Also, since there is often less coding on the pages and because
CSS separates the design elements from the content, it is easier for search
engines to determine what a page is about and to index it appropriately. Finally,
search engine spiders rely heavily on structural organization (heading (h1, h2, h3,
etc) tags) and CSS allows designers to design those elements as needed and to
place them within the page layout in a way that is most beneficial for search
engine optimization.

Lab # 6

CT-362: Web Engineering Page 14


RAMESH KUMAR TCT-002

Exercise:
1. . Define a function max() that takes two numbers as arguments and returns the largest
of them. Use the if-else construct
Code:

Output:

2. Write a function that takes a single character and returns true of it is vowel and false
otherwise.
Code:

CT-362: Web Engineering Page 15


RAMESH KUMAR TCT-002

Output:

3. Define a function sum() and multiply() that sums and multiplies all numbers in an
array. E.g; sum([1,2,3,4]) should returm 10 and multiply([1,2,3,4]) should return 24.
Code:

CT-362: Web Engineering Page 16


RAMESH KUMAR TCT-002

Output:

4. Define a function reverse () that reverses the string supplied to it.

CODE:

CT-362: Web Engineering Page 17


RAMESH KUMAR TCT-002

OUTPUT:

5. Create a HTML form that has number of textboxes when the form runs in the browser
fill the textboxes with data. Write a script that verifies that all the text boxes have been
filled. If a textbox is left empty pop up an alert indicating which box has been left empty.
When the OK button of alert is clicked, the focus must be transferred to that specific
textbox otherwise display THANK YOU.
Code;

CT-362: Web Engineering Page 18


RAMESH KUMAR TCT-002

<form action="">
<label>First Name: <input type="text"
Output:
id="fname"></label><br>
<label>Last Name: <input type="text"
id="lname"></label><br>
<label>Email: <input type="text"
id="email"></label><br>
<label>Address: <input type="text"
id="add"></label><br>
<label>Phone: <input type="text"
id="phone"></label><br>
<input type="button" onclick="checkForm()"
value="submit">
</form>
<script>
function focusField(fieldName) {
document.getElementById(fieldName).focus();
}

function checkForm() { After click on submit button


var fname =
document.getElementById("fname").value;
var lname =
document.getElementById("lname").value;
var email =
document.getElementById("email").value;
var address =
document.getElementById("add").value;
var phone =
document.getElementById("phone").value;

if (!fname.trim()) {
alert("First Name field is empty");
focusField("fname")
} else if (!lname.trim()) {
alert("Last Name field is empty");
focusField("lname")
} else if (!email.trim()) {
alert("Email")
("field is empty ");
focusField("email")
} else if (!address.trim()) {
alert("Address field is empty");
focusField("add")
} else if (!phone.trim()) {
alert("Phone no field is empty");
focusField("phone");
} else
alert("THANK YOU");
}
</script>

Lab # 7
Exercise:
1. Write down the advantages of server side scripting in ASP.Net

CT-362: Web Engineering Page 19


RAMESH KUMAR TCT-002

1) It allows for separation of concern


ASP.NET follows the MVC architecture, which allows for separate input, process and output of
the application. This three-tier architecture, Model-View- Controller has interconnected parts, and
can handle specific development aspects of software applications.
2) Reduces coding time
The framework technology is a big help in reducing coding time, especially when you are
developing big applications. There are different types of code reviews, so you have no chance of
writing a bad code. Code reviews would help you improve code quality.
3) Consists of some of out-of- the box features
ASP.NET delivers enhanced performance and scalability. It also comes with features like just-in-
time compilation, early binding, native optimisation and caching services, and they too serve to
improve performance several notches higher. The codes here are not interpreted like traditional
ASP pages.
4) World class toolbox
The framework comes with incredibly rich toolbox through its Visual Studio integrated
development environment. This toolbox acts as a very important building framework for the
framework, and aids the developer to create applications very quickly. The toolbox is famous for
its features like drag-and-
drop server controls WYSIWYG editing, and automatic deployment.
5) Delivers power and flexibility
The framework language is based on common language runtime, so all the web application
developers can enjoy flexibility and power of that entire platform. It is also language independent,
so you can choose the language for your application or even divide your application across several
languages.
6) Simplicity
Each task can be performed easily, even the most common ones to the complicated and tricky
ones. The common language runtime makes development process a simple one, with services like
garbage collection and automatic reference counting. The framework lets you build user interfaces
that can separate application logic and presentation code.
7) Customizability and Extensibility
The well factored architecture of the framework is a major help to developers. You can easily
extend or replace the subcomponent of the ASP.NET runtime with the help of your own custom-
prepared components. Implementing those have become even easier.
8) Security
Security is a good feature of the framework language. You can develop secure applications
through built in Windows authentication and per-application configuration features.
9) Manageability
The excellent manageability feature of the framework is contributed through its text based
hierarchical configuration system. And since these configurations are incorporated as plain texts,
you can just make use of the local administration tools to apply the new settings. This makes tasks

CT-362: Web Engineering Page 20


RAMESH KUMAR TCT-002

much easier, with no server restart, or with the necessity to deploy them separately, or replace
running compiled code.
10) Benefit of continuous monitoring

Continuous and constant monitoring is an incredible feature of ASP.NET. You don’t have to
worry about the status of the applications, components and the pages themselves. The program
watches out for any such illegal events, and if anything happens (for example, memory leaps of
infinite loops), it would immediately rise into action by destroying the activities, and restarting
itself.
11) Cross-platform migration
The framework language allows for easy cross-platform migration, configuration and deployment
services.

LAB # 8
1. Design a Login.aspx Page and apply field validations on it

<body>
    <form id="form1" runat="server">
        <div>
            <table style="width:100%;">

CT-362: Web Engineering Page 21


RAMESH KUMAR TCT-002

                <caption class="style1">
                    <strong>Login Form</strong>
                </caption>
                <tr>
                    <td class="style2">
                        Username:</td>
                    <td>
                        <asp:TextBox ID="TextBox1"
runat="server"></asp:TextBox>
                    </td>
                    <td>
                        <asp:RequiredFieldValidator
ID="RequiredFieldValidator2" runat="server"
                            ControlToValidate="TextBox1"
ErrorMessage="Please Enter Your Username" ForeColor="Red">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td class="style2">
                        word:</td>
                    <td>
                        <asp:TextBox ID="TextBox2" TextMode="word"
runat="server"></asp:TextBox>
                    </td>
                    <td>
                        <asp:RequiredFieldValidator
ID="RequiredFieldValidator1" runat="server"
                            ControlToValidate="TextBox2"
ErrorMessage="Please Enter Your word" ForeColor="Red">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td class="style2">
                    </td>
                </tr>
                <tr>
                    <td class="style2">
                    </td>
                    <td>
                        <asp:Button ID="Button1" runat="server"
Text="Log In" onclick="Button1_Click" />
                    </td>
                    <td>
                        <asp:Label ID="Label1"
runat="server"></asp:Label>
                    </td>

CT-362: Web Engineering Page 22


RAMESH KUMAR TCT-002

                </tr>
            </table>
        </div>
    </form>
</body>
OUTPUT:

1. public partial class _Default: System.Web.UI.Page {  
2.     protected void Page_Load(object sender, EventArgs e) {  
3.   
4.     }  
5.     protected void Button1_Click(object sender, EventArgs e) {  
6.         SqlConnection con = new SqlConnection(@  
7.         "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\
Database.mdf;Integrated Security=True;User Instance=True");  
8.         SqlCommand cmd = new SqlCommand("select * from tbl_data whe
re username=@username and word=@word", con);  
9.         cmd.Parameters.AddWithValue("@username", TextBox1.Text);  
10.         cmd.Parameters.AddWithValue("word", TextBox2.Text);  
11.         SqlDataAdapter sda = new SqlDataAdapter(cmd);  
12.         DataTable dt = new DataTable();  
13.         sda.Fill(dt);  
14.         con.Open();  
15.         int i = cmd.ExecuteNonQuery();  
16.         con.Close();  
17.   
18.         if (dt.Rows.Count > 0) {  
19.             Response.Redirect("Redirectform.aspx");  
20.         } else {  
21.             Label1.Text = "Your username and word is incorrect";  
22.             Label1.ForeColor = System.Drawing.Color.Red;  
23.   
24.         }  
25.   
26.   
27.     }  
28. }  

LAB # 11
Write any simple PHP script that performs some mathematical operations and
attach the screenshot of the output. ?

Ans: <?php
$x = 10; $y = 20;
echo "The sum of ".$x." and ".$y." is ".($x + $y)."<br />"; echo "The difference of ".$x."
and ".$y." is ".($x - $y)."<br />"; echo "The product of ".$x." and ".$y." is ".($x *
$y)."<br />"; echo "The division of ".$x." and ".$y." is ".($x/$y)."<br />"
?>

CT-362: Web Engineering Page 23


RAMESH KUMAR TCT-002

Output:

LAB #12
Write PHP code to declare an associative array of six elements that has
supermarket item names associated with their price. Use a function to
calculate the total price of all items purchased. Print the array using for each
loop followed by the total cost of items. The program should output the
following text on the browser screen:
Ans:
<html>
<body >
<!-- lab12 -->
<h2>LAB 12 </h2> <?php
$cart = ['cereal' => "5.00", 'coffee beans' => "2.50", 'bananas' => "3.50", 'onion' =>
"1.00", 'lettuce' => "2.40", 'tomato' => "1.00"];
$total = 0;
print_r($cart);
foreach($cart as $product => $price)
{ echo "<br>" . $product . " costs $" . $price;
$total += $price;
}
echo "<br> The total price of your items is $" . $total; ?>
</body>
</html >
LAB #13

Write a simple PHP script to create database, tables and then insert some
dummy data. And attach the screenshot of the output

CREATING DATABASE
Ans:

<?php
$servername = "localhost";

CT-362: Web Engineering Page 24


RAMESH KUMAR TCT-002

$username = "root";
$password = "";

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Create database
$sql = "CREATE DATABASE test1";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}

$conn->close();
?>

CREATING TABLE
<?php
$servername = "localhost";
$username = "root";
$password = "";
$databasename = "mysql";
// CREATING CONNECTION
$conn = mysqli_connect($servername, $username,
$password, $databasename); if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully<br>";
//CREATING TABLE "Student"
$std_query = "CREATE TABLE Student (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

CT-362: Web Engineering Page 25


RAMESH KUMAR TCT-002

firstname
VARCHAR(30)
NOT NULL,
lastname
VARCHAR(30)
NOT NULL, gender
VARCHAR(30)
NOT NULL,
deptname
VARCHAR(20)
NOT NULL, email
VARCHAR(22)
NOT NULL
)";
if
(mysqli_query($c
onn, $std_query))
{ echo "Table
Student created
successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
?>

INSERTING DATA
<?php
$dbhost = "localhost";
$dbuser = "root";

CT-362: Web Engineering Page 26


RAMESH KUMAR TCT-002

$dbpass = "";
// CREATING
CONNECTION
$conn = new
mysqli($dbhost,
$dbuser, $dbpass); if
(!$conn) {
die("Connection
failed: " .
mysqli_connect_error
());
}
echo "Connected
successfully<br>";

$create_db =
"CREATE
DATABASE
abcDB"; if ($conn-
>query($create_db)
=== TRUE)
{ echo nl2br("\
n")."Database
created
successfully";
} else {
echo "Error creating
database: " . $conn-
>error;}

$create_table =
"CREATE TABLE
abcDB.student
( firstname
VARCHAR(45),
lastname
VARCHAR(45),
gender
VARCHAR(45),
deptname
VARCHAR(45),
email VARCHAR(45)
);";
if ($conn-
>query($create_table)
=== TRUE) { echo
nl2br("\n")."Table
created successfully";

CT-362: Web Engineering Page 27


RAMESH KUMAR TCT-002

} else {
echo "Error creating
table: " . $conn-
>error;
}

// INSERTION
OPERATION INTO
TABLE
$sql_insert = "INSERT INTO abcDB.student(firstname, lastname, gender,
deptname, email)
VALUES ('MUZAMIL', 'MEMONN',
'Male', 'SE',
'[email protected]')"; if
(mysqli_query($conn, $sql_insert)) { echo
"New record created successfully";
} else {
echo "Error: ".
"<br>" .
mysqli_error($conn);
}
?>

LAB #14
1. Write a simple PHP script to connect to the database and perform some simple
operations like SELECT, INSERT, UPDATE, DELETE etc. and attach the
screenshot of the output

Ans: Select:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test1";

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

CT-362: Web Engineering Page 28


RAMESH KUMAR TCT-002

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql_select = "SELECT * FROM student";
$result = mysqli_query($conn, $sql_select);

if (mysqli_num_rows($result) > 0) {
echo "DATA IN TABLE EMPLOYEES AFTER SELECTION IS " . "<br>";
// output data of each row
while($row = mysqli_fetch_assoc($result)) { echo "id: " .
$row["id"]. " - First Name: " . $row["firstname"]. "-Last Name: " .
$row["lastname"]. "- Gender: ".$row['gender']. "- Email: ".$row['email'].
"<br><br>";
}
}else {
echo "0 results";
}
mysqli_close($conn);
?>
OUTPUT

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

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

CT-362: Web Engineering Page 29


RAMESH KUMAR TCT-002

$sql_insert = "INSERT INTO student(firstname, lastname, gender, deptname, email)


VALUES ('QURESHI', 'HASSAN', 'Male', 'Computer Science', '[email protected]')"; if
(mysqli_query($conn, $sql_insert)) { echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn); }
mysqli_close($conn);
?>

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

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

$sql = "UPDATE Student SET deptname='Software' WHERE id=2"; if


(mysqli_query($conn, $sql)) { echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn); }
mysqli_close($conn);
?>

DELETE
<?php
$servername = "localhost";

CT-362: Web Engineering Page 30


RAMESH KUMAR TCT-002

$username = "root";
$password = "";
$dbname = "test1";

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

$sql = "DELETE FROM


Student WHERE id=2"; if
(mysqli_query($conn, $sql))
{ echo "Record deleted
successfully";
} else {
echo "Error deleting record: " .
mysqli_error($conn);
}
mysqli_close($conn);
?>

CT-362: Web Engineering Page 31

You might also like