RS3790 - Grade - 12 Practical Material
RS3790 - Grade - 12 Practical Material
Computer Engineering
Practical Book
Government of Nepal
Ministry of Education, Science and Technology
Curriculum Development Centre
Sanothimi, Bhaktapur
Phone : 5639122/6634373/6635046/6630088
Website : www.moecdc.gov.np
Feedback Copy
Practical Book
(Grade 12)
Secondary Level
Computer Engineering
Government of Nepal
Ministry of Education, Science and Technology
Curriculum Development Centre
Sanothimi, Bhaktapur
Publisher : Government of Nepal
Ministry of Education, Science and Technology
Curriculum Development Centre
Sanothimi, Bhaktapur
© Publisher
3. Carefully place the NIC into the slot making the proper connection. It should
be well placed and tight in the slot
4. Close the case and power on the cable and turn on the computer. To verify
the installation go to computer properties/ device manager/network adaptor,
C Programming : Grade 9 1
here you can see the NIC we installed in the computer.
Conclusion
After following the steps, the network interface card and the devices like hub and
switch can be installed successfully.
2 C Programming : Grade 9
Installation and configuration of workstation PC
Introduction
A workstation is a special computer designed for technical or scientific
applications. Intended primarily to be used by one person at a time, they are
commonly connected to a local area network and run multi-user operating systems.
Work stations usually have high specifications than the computer available in the
market. They are used for server and other research and data processing purposes.
We can say the workstation as the advanced form of pc having high memory high
cores higher graphics.
Requirements
(i) Workstation (ii) Monitors (iii) Cooling System (iv) VGA or DVI Port
Steps
1. The installation and configuration of workstation is almost same as the
normal pc
2. The multiple monitors are connected using VGA or DVI port
3. Go to the display settings and go to multitasking and choose the
recommended setting
4. Cooling system is most as these computer generates too much heat
Conclusion
After following the steps, the installation and configuration of workstation PC can
be achieved successfully.
C Programming : Grade 9 3
Setup client server networking and verify it
Introduction to client server networking
Server to client computer networks are common in businesses and can be useful in
homes as well. This is different from simply connecting computers to a router to
use the Internet, because another type of device or computer is set up as the server,
which the other computers connect to. This type of network allows you to centrally
manage the computers in the network and share files and printers with each
computer. A server to client network works well in situations where you have more
than three computers and you want to be able to access a resource, such as files or
a printer, on all of the connecting computers. You should have at least a basic
understanding of how computer networks work to complete this project.
4 C Programming : Grade 9
2. Open the server management program on your Windows Server. Do this by
clicking "Manage Your Server" from the start menu. Click "Add or Remove
a Role." A new window will open with configure your server wizard. Click
"Next." A list of the different functions your server can perform is then
displayed. Select "Domain Controller (Active Directory)" and press "Next."
Click "Next" again to begin the active directory installation.
3. Click "Next" on the installation wizard until reaching the page where you can
select the option to specify that you are setting up a domain controller for a
new domain. Press "Next" and then select "Domain in a New Forest." Type a
name for your domain. This will be the name of your network. Click "Next"
and a name will be displayed that will be used if your network contains a
computer running an older version of Windows.
4. Click "Next" until reaching the step called "DNS Registration Diagnostics."
Select the option to "Install and configure the DNS server on this computer,"
and then set this computer to "Use this DNS server as its preferred server."
Click "Next" until reaching the screen where you must enter a password for
the administrator. Click "Next" and run the installation. Insert the server
installation disc if required. Restart the computer to complete the installation
when prompted to.
5. Reopen the Manage your Server program. Click "Manage Users and
Computers in Active Directory." Add a computer object for each computer in
the domain. Add user accounts for each user that will log on as well.
6. On each computer in the network, open the system properties from under
control panel. Click "Change..." on the computer name tab. Click "Domain"
and then enter the name of the domain. Enter a user name and password for
the domain when prompted. Restart the computer. You can now access the
domain and log on to the server.
Conclusion
After following the steps the client server networking can be achieved
C Programming : Grade 9 5
Familiarization with basic network commands: Observing IP
address and MACaddress, Setting IP address and default
gateway in PC, verifying network layerconnectivity
Introduction
Network commands are the commands which are entered in a command line
interface to know the status of the network. The network commands can be entered
in either windows environment, Linux environment as well as MAC interface. In
this experiment we see the commands in the windows as it is the most familiar
operating system
Requirements
(a) Computer (b) Internet connection (c)Router
Steps to observe IP address and mac address in windows
1. Go to start menu and click on run or press windows key +R
2. Type cmd and press enter. A black window appears on your screen
3. Type ipconfig and press enter
IP ADDRESS
Default gateway
6 C Programming : Grade 9
4. Type ipconfig/all to view the all present mac address in your computer
The highlighted parts of the above pictures are the mac address of the computer
system. They are also termed as physical address. The first MAC is for wireless
LAN local area connection. The second is for the wireless LAN adapter Wi-Fi and
the third one is for Bluetooth network connection.
To change the ip and default gateway using CMD
The steps to be performed to change the ip and default gateway are as follows:
1. First open the command prompt as administrator
2. To change the default gateway enter the command netshintip set address
"Ethernet0" static 192.168.1.10 255.255.255.0 192.168.1.1
C Programming : Grade 9 7
To verify the network layer connectivity
To verify the network layer connectivity the command we use is ping. This
command is used to test or verify the connection of internet protocol using the
network.
1. The steps to verify network layer connectivity is:
Open CMD
2. Type the following command ping www.google.com -t
This shows the above information to verify the network connection. You can use
any other site instead of google.com to check the ping of the network and verify
network connectivity
Conclusion
Hence the IP address, Default gateway, MAC address was viewed and changed
successfully and network layer connectivity was verified.
8 C Programming : Grade 9
Setup Peer to Peer network and verify it
Introduction
Peer to peer network is a network in which all the workstations behaves as sender
as well as receiver. In this type of network all the computers have equal access to
all the components in the network.
C Programming : Grade 9 9
Cabling: construction of straight through and cross over cable
and verify the physical level connectivity
Introduction
A straight through cable is a type of twisted pair cable that is used in local area
networks to connect a computer to a network hub such as a router. This type of
cable is also sometimes called a patch cable and is an alternative to wireless
connections where one or more computers access a router through a wireless signal.
On a straight through cable, the wired pins match. Straight through cable use one
wiring standard: both ends use T568A wiring standard or both ends use T568B
wiring standard. The following figure shows a straight through cable of which both
endsare wired as the T568B standard. The patch cable contains 4 pair ofcolor mode.
The full color wire is used for data transmission and partial color wires are used for
power transmission.
10 C Programming : Grade 9
Steps to verify the physical layer connectivity
The easiest way to verify the physical layer connectivity to ping the network on
which the cables is used. Successful ping means the physical layer connectivity is
verified and unsuccessful ping means that the physical layer isn’t verified. The steps
to verify physical layer connectivity are as follows:
1. Go to start menu and go to run command or press Windows + R to open run
command
2. Type CMD to open command prompt
3. Type the ping command along with the IP of the device connected by the
cable
for e.g. ping 10.1.20.20 –t
Successful ping
Conclusion
After following the steps, Ethernet Cable connectivity using RJ45 can be achieved
using standard color codes and files can be shared using the same Ethernet Cable
between two end devices.
C Programming : Grade 9 11
Demonstrate AM and FM modulation and demodulation
schemes using trainer kit
Introduction
Modulation is a process of mixing a signal with a sinusoid to produce a new signal.
This new signal, conceivably, will have certain benefits over an un-modulated
signal. Mixing of low frequency signal with high frequency carrier signal is called
modulation.
AM stands for Amplitude Modulation and FM stands for Frequency Modulation.
In amplitude modulation, amplitude varies with keeping phase and frequency
constant. In frequency modulation, frequency varies keeping amplitude and phase
constant. So for the demonstration we need the following requirements
Requirements
(a) Trainer Kit (b) Oscilloscope (c) Wires (d) Functional Generator
Steps
1. Connect the trainer kit with the oscilloscope and give power to both
2. Connect the input from function generator to output of FM modulation to
the oscilloscope with cables and observe message signal and carrier signal on
oscilloscope
3. Change the input message signal and measure the carrier signal frequency
4. Repeat the process for modulation and demodulation process of AM and FM
Note the corresponding AM and FM values for both modulation and demodulation
12 C Programming : Grade 9
Understanding router interface and basic routing using
routing simulator
Introduction
Routing simulator is a software which is used to design the network without
physically connecting the devices. This software allows you to develop a logical
network all types of topologies using the software. It saves the bunch of time. It is
used before constructing the network and to choose the best networking topology
suitable for the network
Requirements
(a) Computer (b) Cisco Simulator (Packet Tracer)
Steps
1. Open the cisco packet tracer ( download the packet tracer from
www.download.com)
2. Click on the router symbol 1A for one router and click on the workspace
3. Choose pc from the end devices and place it in the workspace and repeat for
C Programming : Grade 9 13
another pc
4. To connect them choose connection and click on copper crossover cable
5. Click on the router and go to the CLI (command line interface) tab
6. Type no to disable graphical mode
7. Type enable to start the command line interface mode for the router
8. Type router> for basic routing information of the router.
Conclusion :
Hence, the basic routing and routing interface was verified using routing simulator.
14 C Programming : Grade 9
WEB DEVELOPMENT AND DATABASE
Introduction
Web development broadly refers to the tasks associated with developing websites
for hosting via intranet or internet. The web development process includes web
design, web content development, client-side/server-side scripting and network
security configuration, among other tasks. Web development is also known as
website development.
A database (DB), in the most general sense, is an organized collection of data. More
specifically, a database is an electronic system that allows data to be easily
accessed, manipulated and updated. In other words, a database is used by an
organization as a method of storing, managing and retrieving information. Modern
databases are managed using a database management system (DBMS).
This book contains the practical workouts that need to be performed on lab by
students. For the proper performance of the workouts it is necessary to have the
following requirements
Requirements
(a) Computer system (b) Javascript (c) PHP (d) Xamp
(e) Database (f) Wamp (e) Web browser (f) Easy Php
C Programming : Grade 9 15
Unit: 1
HTML
Design a web page to describe web skeleton
The basic structure of web skeleton is:
<html>
<head>
<title>Page title</title>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
The output of the structure will be
16 C Programming : Grade 9
</head>
<body>
The <b>bold</b> element and the
<strong>strong</strong> element are the same.<br>
<i>The italics element renders text in italics.</i><br />
<em>The emphasis element also produces italicized text.</em><br />
<cite>The cite element identifies a citation.</cite><br />
<var>The var element marks a variable.</var><br />
<dfn>The dfn element stands for a defining instance.</dfn><br />
<address>The address element marks off address or author
information.</address><br />
The <sup>superscript</sup> and <sub>subscript</sub> elements.
To display <s>strikethrough</s> text, use the <strike>strike
</strike> or the <del>deleted</del> elements.<br />
Use the <ins>inserted text</ins> element or the
<u>underline</u> element for underlining text.
</body>
</html>
The output will be the following
C Programming : Grade 9 17
Create list and insert image
<html>
<head><title>Unordered Lists</title><head>
<body>
<ul>
<li>This is the first item
<ul>
<li>This is a sub point</li>
<li>This is another sub point</li>
</ul></li>
<li>This is the second item
<ul>
<li>This is a sub point</li>
<li>This is another sub point</li>
</ul></li>
<li>This is the third item
<ul>
<li>This is a sub point</li>
<li>This is another sub point</li>
</ul></li>
</ul>
<imgsrc="new.jpg"
align="left" width="100" height="100"></p>
</body>
</html>
18 C Programming : Grade 9
The output will be as follows:
Create hyperlink
<html>
<body>
<h2>HTML Links</h2>
<p><a href="https:www.google.com">Visit the search engine/a></p>
</body>
</html>
Output
Local Links
The example above used an absolute URL (a full web address).
A local link (link to the same web site) is specified with a relative URL (without
https://www....)
C Programming : Grade 9 19
Example
<a href="html_images.asp">HTML Images</a>
HTML Links - Create a Bookmark
HTML bookmarks are used to allow readers to jump to specific parts of a Web
page.
Bookmarks can be useful if your webpage is very long.
To make a bookmark, you must first create the bookmark, and then add a link to it.
When the link is clicked, the page will scroll to the location with the bookmark.
Example
First, create a bookmark with the id attribute:
<h2 id="C4">Chapter 4</h2>
Then, add a link to the bookmark ("Jump to Chapter 4"), from within the same page:
<a href="#C4">Jump to Chapter 4</a>
Or, add a link to the bookmark ("Jump to Chapter 4"), from another page:
Example
<a href="html_demo.html#C4">Jump to Chapter 4</a>
Create table with properties
<html>
<body>
<h4>Cell that spans two columns:</h4>
<table border="4">
<tr><th>Name</th>
<thcolspan="2">Loan No</th></tr>
<tr><td>Jones</td>
<td>L-1</td>
<td>L-2</td></tr></table>
<h4>Cell that spans two rows:</h4>
<table border="8">
20 C Programming : Grade 9
<tr><th>Name</th>
<td>Jones</td></tr><tr>
<throwspan="2">Loan No</th>
<td>L-1</td></tr><tr>
<td>L-2</td></tr>
</table>
</body>
</html>
The output will be the following
C Programming : Grade 9 21
<input type="radio" checked="checked" name="sex" value="male" />
Male</br>
<input type="radio" name="sex" value="female" /> Female
<p>Birthday <input type="text" name="T6" size="05">
<select size="1" name="D2">
<option>-Select One-</option>
<option>January</option>
<option>February</option>
<option>March</option></select>
<input type="text" name="T7" size="10"></p>
TypeYourself<textarea rows="4" name="S1" cols="20"></textarea>
<br><input type="submit" value="Accept" name="B1"><input type="reset"
value="Cancel" name="B2"></br>
</form>
</body>
</html>
The output will be the following
22 C Programming : Grade 9
Create frame
<html>
<frameset cols="25%,*,25%">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
<frame src="frame_c.htm">
</frameset>
</html>
The output will be the following
C Programming : Grade 9 23
Unit: 2
Javascript
C Programming : Grade 9 25
Apply array
<head>
<body>
<script>
var numbers = [10, 20, 30];
// Print the array elements.
document.write("Array: " + numbers + "; ");
// Get length of array.
var length = numbers.length;
document.write("Length: " + length);
</script>
</body>
</html>
Output
Array: 10,20,30; Length: 3
Demonstrate different types of event handling
<html>
<head>
<script type = "text/javascript">
<!--
functionsayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
26 C Programming : Grade 9
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>
The output will be a button on which clicked will display “say hello”
Design and develop form to validation of data
<html>
<head>
<script>
functionvalidateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="/action_page.php" onsubmit="return
validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
The output will be it will ask for name and after you enter your name then there will
be submit button and after submitting the name you given will be validated on
screen
C Programming : Grade 9 27
Apply basic structure of jquery
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></scr
ipt>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p id="test">This is another paragraph.</p>
<button>Click me</button>
</body>
</html>
The output will be
This is a heading
This is a paragraph.
Click me
28 C Programming : Grade 9
Unit: 3
Cascading style sheet
C Programming : Grade 9 29
The output will be
This is a heading
This is a paragraph.
30 C Programming : Grade 9
<style>input {
width: 100%;
}
</style>
<body>
<img style = "border:0px;" src = "nepal.jpeg" />
table.one {border-collapse:collapse;}
table.two {border-collapse:separate;}
td.a {
border-style:dotted;
border-width:3px;
border-color:#000000;
padding: 10px;
}
td.b {
border-style:solid;
border-width:3px;
border-color:#333333;
padding:10px;
}
<ul style = "list-style-type:circle;">
<li>Maths</li>
<li>Social Science</li>
<li>Physics</li>
</ul>
<p>A full-width input field:</p>
<form>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname">
C Programming : Grade 9 31
</form>
</body>
</html>
The output of the program will generate a flag of Nepal, a simple table, a list
and a form asking name.
Design layouts
<html lang="en">
<head>
<title>CSS Website Layout</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
margin: 0;
}
/* Style the header */
.header {
background-color: #f1f1f1;
padding: 20px;
text-align: center;
}
</style>
</head>
<body>
<div class="header">
<h1>Header</h1>
</div>
</body>
32 C Programming : Grade 9
</html>
Design CSS responsive
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
*{
box-sizing: border-box;
}
.menu {
float: left;
width: 20%;
}
.menuitem {
padding: 8px;
margin-top: 7px;
border-bottom: 1px solid #f1f1f1;
}
.main {
float: left;
width: 60%;
padding: 0 20px;
overflow: hidden;
}
.right {
background-color: lightblue;
float: left;
width: 20%;
padding: 10px 15px;
C Programming : Grade 9 33
margin-top: 7px;
}
@media only screen and (max-width:800px) {
/* For tablets: */
.main {
width: 80%;
padding: 0;
}
.right {
width: 100%;
}
}
@media only screen and (max-width:500px) {
/* For mobile phones: */
.menu, .main, .right {
width: 100%;
}
}
</style>
</head>
<body style="font-family:Verdana;">
<div style="background-color:#f1f1f1;padding:15px;">
<h1>Cinque Terre</h1>
<h3>Resize the browser window</h3>
</div>
<div style="overflow:auto">
<div class="menu">
<div class="menuitem">The Walk</div>
<div class="menuitem">Transport</div>
34 C Programming : Grade 9
<div class="menuitem">History</div>
<div class="menuitem">Gallery</div>
</div>
<div class="main">
<h2>The Walk</h2>
<p>The walk from Monterosso to Riomaggiore will take you approximately
two hours, give or take an hour depending on the weather conditions and your
physical shape.</p>
<imgsrc="img_5terre.jpg" style="width:100%">
</div>
<div class="right">
<h2>What?</h2>
<p>Cinque Terre comprises five villages: Monterosso, Vernazza, Corniglia,
Manarola, and Riomaggiore.</p>
<h2>Where?</h2>
<p>On the northwest cost of the Italian Riviera, north of the city La
Spezia.</p>
<h2>Price?</h2>
<p>The Walk is free!</p>
</div>
</div>
<div style="background-color:#f1f1f1;text-align:center; padding:10px;
margin-top:7px; font-size:12px;"> This web page is a part of a demonstration
of fluid web design made by w3schools.com. Resize the browser window to
see the content respond to the resizing.</div>
</body>
</html>
C Programming : Grade 9 35
Unit: 4
Install PHP and configure
36 C Programming : Grade 9
variable. Open Settings, type ‘environment variables’ into the
search field and open the result. Select the “Advanced” tab, and click the
“Environment Variables” button.
Scroll down the System variables list and click on “Path” followed by the “Edit”
button. Click “Edit text” and add ;C:\php to the end of the Variable value line
(remember the semicolon).
C Programming : Grade 9 37
The following lines should be changed:
On line 239, add index.php as a default file name:
DirectoryIndexindex.php index.html
At the bottom of the file, add the following lines (change the PHP file locations if
necessary):
# PHP5 module
LoadModule php5_module "c:/php/php5apache2_2.dll"
AddType application/x-httpd-php .php
PHPIniDir "C:/php"
Save the configuration file and test it from the command line (Start > Run >cmd):
cd Apache2bin
httpd–t
Step 6: Test a PHP file
Create a file named index.php in Apache’s web page root (either htdocs or
D:WebPages) and add this code:
<?phpphpinfo(); ?>
Installing MySQL and configure
Step 1: download MySQL
Download MySQL from dev.mysql.com/downloads/. Follow MySQL Community
Server, Windows and download the “Without installer” version.
Step 2: Extract the files
We will install MySQL to C:mysql, so extract the ZIP to your C: drive and rename
the folder from “mysql-x.x.xx-win32” to “mysql”.
MySQL can be installed anywhere on your system. If you want a lightweight
installation, you can remove every sub-folder except for bin, data, scripts and share.
38 C Programming : Grade 9
Step 3: Create a configuration file
MySQL provides several configuration methods but, in general, it is easiest to to
create a my.ini file in the mysql folder. There are hundreds of options to tweak
MySQL to your exact requirements, but the simplest my.ini file is:
[mysqld]
# installation directory
basedir="C:/mysql/"
Step 4: Test your installation
The MySQL server is started by running C:mysqlbinmysqld.exe. Open a command
box (Start > Run >cmd) and enter the following commands:
cdmysqlbin
mysqld
This will start the MySQL server which listens for requests on localhost port 3306.
You can now start the MySQL command line tool and connect to the database.
Open another command box and enter:
cdmysqlbin
mysql -u root
This will show a welcome message and the mysql> prompt. Enter “show
databases;” to view a list of the pre-defined databases.
C Programming : Grade 9 39
it again.
Step 2: Extract the files
We will install Apache in C:Apache2, so extract the ZIP file to the root of the C:
drive.
Apache can be installed anywhere on your system, but you will need to change the
configuration file paths accordingly…
Step 3: Configure Apache
Apache is configured with the text file confhttpd.conf contained in the Apache
folder. Open it with your favourite text editor.
Note that all file path settings use a ‘/’ forward-slash rather than the Windows
backslash. If you installed Apache anywhere other than C:Apache2, now is a good
time to search and replace all references to “c:/Apache2”.
There are several lines you should change for your production environment:
Line 46, listen to all requests on port 80:
Listen *:80
Step 5: Test your installation
Your Apache configuration can now be tested. Open a command box (Start > Run
>cmd) and enter:
cd Apache2bin
httpd -t
Correct any httpd.conf configuration errors and retest until none appear.
Step 6: Install Apache as a Windows service
The easiest way to start Apache is to add it as a Windows service. From a command
prompt, enter:
cd Apache2bin
httpd -k install
Open the Control Panel, Administrative Tools, then Services and double-click
40 C Programming : Grade 9
Apache2.2. Set the Startup type to “Automatic” to ensure
Apache starts every time you boot your PC.
Alternatively, set the Startup type to “Manual” and launch Apache whenever you
choose using the command “net start Apache2.2”.
Step 7: Test the web server
Create a file named index.html in Apache’s web page root (either htdocs or
D:WebPages) and add a little HTML code:
<html>
<head><title>testing Apache</title></head>
<body><p>Apache is working!</p></body>
</html>
Ensure Apache has started successfully, open a web browser and enter the address
http://localhost/. If all goes well, your test page should appear.
Integrate PHP and HTML
<html>
<body>
<div class="menu">
<?php include 'menu.php';?>
</div>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
</body>
</html>
//The menu.php contains the following code
C Programming : Grade 9 41
<?php
echo '<a href="/default.asp">Home</a> -
<a href="/html/default.asp">HTML Tutorial</a> -
<a href="/css/default.asp">CSS Tutorial</a> -
<a href="/js/default.asp">JavaScript Tutorial</a> -
<a href="default.asp">PHP Tutorial</a>';
?>
The output will be
Home - HTML Tutorial - CSS Tutorial - JavaScript Tutorial - PHP Tutorial
Welcome to my home page!
Some text.
Some more text.
42 C Programming : Grade 9
Unit: 5
PHP
C Programming : Grade 9 43
break;
default:
echo "Wonder which day is this ?";
}
?>
</body>
</html>
It will produce the following result −
Today is Monday
Create function and pass the values
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
FunctionaddFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value";
?>
</body>
</html>
44 C Programming : Grade 9
Create array and objects
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
C Programming : Grade 9 45
Value is one
Value is two
Value is three
Value is four
Value is five
46 C Programming : Grade 9
Unit: 6
Working with form
C Programming : Grade 9 47
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows
dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
48 C Programming : Grade 9
} else {
$gender = test_input($_POST["gender"]);
}
}
functiontest_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars
($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo
$website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo
$comment;?></textarea>
C Programming : Grade 9 49
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) &&
$gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) &&
$gender=="male") echo "checked";?> value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) &&
$gender=="other") echo "checked";?> value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
50 C Programming : Grade 9
The output will be
C Programming : Grade 9 51
}else {
echo "Message could not be sent...";
}
?>
</body>
</html>
Upload file
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP File Upload</title>
</head>
<body>
<?php
if (isset($_SESSION['message']) && $_SESSION['message'])
{
printf('<b>%s</b>', $_SESSION['message']);
unset($_SESSION['message']);
}
?>
<form method="POST" action="upload.php" enctype="multipart/form-
data">
<div>
<span>Upload a File:</span>
<input type="file" name="uploadedFile" />
52 C Programming : Grade 9
</div>
<input type="submit" name="uploadBtn" value="Upload" />
</form>
</body>
</html>
Create session
<?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>
the session is used in the other program as
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
C Programming : Grade 9 53
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
The output will be:
Session variables are set
Favorite color is green
Favorite animal is cat
54 C Programming : Grade 9
Unit: 7
Database Management system
Create table and apply DDL and DML statement
Create Database College
CREATE TABLE Student(student_id INT, name VARCHAR(100), age INT);
INSERT INTO student(student_id, name,age) values(101, 'Adam',15);
INSERT INTO student(student_id, name,age) values(102, 'Alex',18);
INSERT INTO student(student_id, name,age) values(103, 'Abhi',17);
The output will be like
Eg.
DML commands are Insert Update, Delete etc
DDL commands are Drop, Create
C Programming : Grade 9 55
Unit: 8
MySQL and PHP
Create a database connection class
//the dbconnection.php should be like
<?php
Class DbConnection{
functiongetdbconnect(){
$conn = mysqli_connect("host","username","password","database") or
die("Couldn't connect");
return $conn;
}
}
?>
//the function.php should be coded like
?php
require_once('Dbconnection.php');
Class WorkingExamples{
functiongetUserInfo($id) {
$Dbobj = new DbConnection();
$query = mysqli_query($Dbobj->getdbconnect(), "SELECT * FROM
users WHERE id = '$id'");
returnmysqli_fetch_array($query);
}
}
56 C Programming : Grade 9
Building User Register Form
Step 1:
The code below creates a simple registration form
<html>
<head>
<title>Registration Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h2>Registration Form</h2>
<form action="registration_form.php" method="POST"> First name:
<input type="text" name="firstname"><br> Last name:
<input type="text" name="lastname">
<input type="hidden" name="form_submitted" value="1" />
<input type="submit" value="Submit">
</form>
</body>
</html>
C Programming : Grade 9 57
Conceptual View
Step 2:
Processing the registration form data
<html>
<head>
<title>Registration Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?php if (isset($_POST['form_submitted'])): ?> //this code is executed when the
form is submitted
<h2>Thank You <?php echo $_POST['firstname']; ?></h2>
<p>You have been registered as
<?php echo $_POST['firstname'] . ' ' . $_POST['lastname']; ?>
</p>
<p>Go <a href="/registration_form.php">back</a> to the form</p>
<?php else: ?>
58 C Programming : Grade 9
<h2>Registration Form</h2>
<form action="registration_form.php" method="POST">
First name:
<input type="text" name="firstname">
<br> Last name:
<input type="text" name="lastname">
<input type="hidden" name="form_submitted" value="1" />
<input type="submit" value="Submit">
</form>
<?phpendif; ? >
</body>
</html>
Develop database connection program to insert update delete and search
options through php form
<?php
$host = "localhost";
$user = "root";
$password ="";
$database = "test_db";
$id = "";
$fname = "";
$lname = "";
$age = "";
mysqli_report(MYSQLI_REPORT_ERROR |
MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
C Programming : Grade 9 59
$connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
echo 'Error';
}
// get values from the form
functiongetPosts()
{
$posts = array();
$posts[0] = $_POST['id'];
$posts[1] = $_POST['fname'];
$posts[2] = $_POST['lname'];
$posts[3] = $_POST['age'];
return $posts;
}
// Search
if(isset($_POST['search']))
{
$data = getPosts()
$search_Query = "SELECT * FROM users WHERE id = $data[0]";
$search_Result = mysqli_query($connect, $search_Query);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($row = mysqli_fetch_array($search_Result))
{
$id = $row['id'];
$fname = $row['fname'];
60 C Programming : Grade 9
$lname = $row['lname'];
$age = $row['age'];
}
}else{
echo 'No Data For This Id';
}
}else{
echo 'Result Error';
}
}
// Insert
if(isset($_POST['insert']))
{
$data = getPosts();
$insert_Query = "INSERT INTO `users`(`fname`, `lname`, `age`)
VALUES ('$data[1]','$data[2]',$data[3])";
try{
$insert_Result = mysqli_query($connect, $insert_Query);
if($insert_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Inserted';
}else{
echo 'Data Not Inserted';
}
}
} catch (Exception $ex) {
echo 'Error Insert '.$ex->getMessage();
C Programming : Grade 9 61
}
}
// Delete
if(isset($_POST['delete']))
{
$data = getPosts();
$delete_Query = "DELETE FROM `users` WHERE `id` = $data[0]";
try{
$delete_Result = mysqli_query($connect, $delete_Query);
if($delete_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Deleted';
}else{
echo 'Data Not Deleted';
}
}
} catch (Exception $ex) {
echo 'Error Delete '.$ex->getMessage();
}
}
// Edit
if(isset($_POST['update']))
{
$data = getPosts();
$update_Query = "UPDATE `users` SET `fname`='$data[1]',
`lname`='$data[2]',`age`=$data[3] WHERE `id` = $data[0]";
try{
62 C Programming : Grade 9
$update_Result = mysqli_query($connect, $update_Query);
if($update_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Updated';
}else{
echo 'Data Not Updated';
}
}
} catch (Exception $ex) {
echo 'Error Update '.$ex->getMessage();
}
}
?>
<!DOCTYPE Html>
<html>
<head>
<title>PHP INSERT UPDATE DELETE SEARCH</title>
</head>
<body>
<form action="php_insert_update_delete_search.php" method="post">
<input type="number" name="id" placeholder="Id" value="<?php echo
$id;?>"><br><br>
<input type="text" name="fname" placeholder="First Name" value="<?php
echo $fname;?>"><br><br>
<input type="text" name="lname" placeholder="Last Name" value="<?php
echo $lname;?>"><br><br>
<input type="number" name="age" placeholder="Age" value="<?php echo
C Programming : Grade 9 63
$age;?>"><br><br>
<div>
<!-- Input For Add Values To Database-->
<input type="submit" name="insert" value="Add">
<!-- Input For Edit Values -->
<input type="submit" name="update" value="Update">
<!-- Input For Clear Values -->
<input type="submit" name="delete" value="Delete">
<!-- Input For Find Values With The given ID -->
<input type="submit" name="search" value="Find">
</div>
</form>
</body>
</html>
The output will be
64 C Programming : Grade 9
functionshowUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 &&this.status==200) {
document.getElementById("txtHint").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">yogeshparajuli</option>
<option value="2">rajeshhamal</option>
<option value="3">kpsharmaoli</option>
<option value="4">puspakamaldahal</option>
</select>
C Programming : Grade 9 65
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
Use captcha
// captcha.php
<?php
session_start();
header ('Content-type: image/png');
$chars = "012345678901234567abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$captcha_text = '';
for ($i = 0; $i< 6; $i++)
{
$captcha_text .= $chars[rand(0, strlen($chars)-1)];
}
$captcha_bg = @imagecreatefrompng("captcha.png");
imagettftext( $captcha_bg, 30, 0, 0, 40, imagecolorallocate ($captcha_bg, 0, 0, 0),
'larabiefont.ttf', $captcha_text );
$_SESSION['captcha'] = $captcha_text;
imagepng($captcha_bg, NULL, 0);
imagedestroy($captcha_bg);
?>
66 C Programming : Grade 9