0% found this document useful (0 votes)
4 views19 pages

Internet Programmingpp

The document covers various aspects of internet programming, focusing on scripting languages, specifically PHP. It includes definitions, capabilities, code examples for tasks such as pay computation, user creation, and database operations, as well as discussions on validation and web server functionalities. Additionally, it highlights the advantages of dynamic websites and the role of MySQL in web applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views19 pages

Internet Programmingpp

The document covers various aspects of internet programming, focusing on scripting languages, specifically PHP. It includes definitions, capabilities, code examples for tasks such as pay computation, user creation, and database operations, as well as discussions on validation and web server functionalities. Additionally, it highlights the advantages of dynamic websites and the role of MySQL in web applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Internet Programming

QUESTION ONE

a) Define Scripting Language (2 Marks)

A scripting language is a programming language designed for integrating and communicating


with other programming languages. It is typically used for automating the execution of tasks that
could alternatively be executed one-by-one by a human operator.

b) Three Capabilities of Scripting Languages (3 Marks)

1. Automation of Tasks: Scripting languages can automate repetitive tasks, such as file
manipulation, batch processing, and system administration tasks.
2. Integration: They can easily integrate with other software applications, allowing
different components of a system to communicate and function together.
3. Rapid Development: Scripting languages enable quick prototyping and development,
allowing developers to write and test code efficiently.

c) PHP Code Using Loop to Output Given Numbers and Squares (6 Marks)

php
Copy code
<?php
echo "Number\tSquare\n";
for ($i = 5; $i >= 1; $i--) {
echo "$i\t" . ($i * $i) . "\n";
}
?>

d) Pay Computation Form and PHP Code for Processing (8 Marks)

i. HTML Form Code:

html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Pay Computation Form</title>
</head>
<body>
<form action="compute_pay.php" method="post">
<label for="employee_name">Employee Names:</label><br>
<input type="text" id="employee_name" name="employee_name"><br>
<label for="employee_id">Employee ID Number:</label><br>
<input type="text" id="employee_id" name="employee_id"><br>
<label for="days_worked">No. of days worked:</label><br>
<input type="number" id="days_worked" name="days_worked"><br>
<label for="daily_pay_rate">Daily pay Rate (Kshs):</label><br>
<input type="number" id="daily_pay_rate" name="daily_pay_rate"><br>
<input type="submit" value="Compute Pay">
</form>
</body>
</html>

ii. PHP Code for Processing Form Data:

php
Copy code
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$employee_name = $_POST['employee_name'];
$employee_id = $_POST['employee_id'];
$days_worked = $_POST['days_worked'];
$daily_pay_rate = $_POST['daily_pay_rate'];

$gross_pay = $days_worked * $daily_pay_rate;


$tax_amount = $gross_pay * 0.16;
$net_pay = $gross_pay - $tax_amount;

echo "Employee Name: $employee_name<br>";


echo "Employee ID: $employee_id<br>";
echo "Gross Pay: Kshs $gross_pay<br>";
echo "Tax Amount (16%): Kshs $tax_amount<br>";
echo "Net Pay: Kshs $net_pay<br>";
}
?>

e) Four Core Features of PHP Language (4 Marks)

1. Cross-Platform: PHP runs on various platforms, including Windows, Linux, and


macOS, making it versatile for different environments.
2. Embedded: PHP can be embedded directly within HTML code, facilitating the creation
of dynamic web pages.
3. Open Source: PHP is free to use and has a large community supporting and developing
it, ensuring continuous improvement and extensive resources.
4. Database Integration: PHP supports integration with multiple database management
systems like MySQL, PostgreSQL, SQLite, and more, making it suitable for data-driven
applications.

f) Declare and Initialize Variables in PHP (2 Marks)

php
Copy code
<?php
$variableName = "Hello, World!";
$number = 42;
$boolean = true;
?>
g) PHP Code for Connecting to MySQL Database Server (5 Marks)

php
Copy code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database_name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "Connected successfully";
}
?>

QUESTION TWO

a) Comments in PHP (5 Marks)

Comments: Comments are annotations in the source code that are ignored by the
compiler/interpreter. They are used to explain the code and make it more understandable.

Two Major Types of Comments in PHP:

1. Single-line Comments: Use // or # for single-line comments.

php
Copy code
// This is a single-line comment
# This is another single-line comment

2. Multi-line Comments: Use /* ... */ for multi-line comments.

php
Copy code
/*
This is a multi-line comment
that spans multiple lines.
*/

b) User Creation Form and PHP Code (10 Marks)

i. HTML Form for Creating New System Users:

html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Create New User</title>
</head>
<body>
<form action="create_user.php" method="post">
<label for="first_name">First Name:</label><br>
<input type="text" id="first_name" name="first_name"><br>
<label for="last_name">Last Name:</label><br>
<input type="text" id="last_name" name="last_name"><br>
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br>
<input type="submit" value="Create User">
</form>
</body>
</html>

ii. PHP Code for Receiving and Inserting New User Details:

php
Copy code
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$username = $_POST['username'];
$password = $_POST['password'];

// Hash the password


$hashed_password = password_hash($password, PASSWORD_DEFAULT);

// Database connection
$servername = "localhost";
$db_username = "root";
$db_password = "";
$dbname = "database_name";

$conn = new mysqli($servername, $db_username, $db_password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Insert user details into the Users table


$sql = "INSERT INTO Users (first_name, last_name, username, password)
VALUES ('$first_name', '$last_name', '$username', '$hashed_password')";

if ($conn->query($sql) === TRUE) {


echo "New user created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
}
?>

c) Array Program to Print Items (5 Marks)

php
Copy code
<?php
$items = array("TV", "Phone", "Radio", "DVD", "CD-ROM");

foreach ($items as $item) {


echo $item . "<br>";
}
?>

QUESTION THREE

a) phpMyAdmin (2 Marks)

phpMyAdmin: phpMyAdmin is a free, open-source web-based administration tool for


managing MySQL and MariaDB databases. It provides a graphical interface to perform various
database operations, such as creating, modifying, and deleting databases, tables, fields, or rows.

b) Four Capabilities of phpMyAdmin (4 Marks)

1. Database Management: Create, modify, and delete databases and tables.


2. Query Execution: Execute SQL queries and view results directly from the web interface.
3. Data Import/Export: Import and export data in various formats, including CSV, SQL,
and XML.
4. User Management: Manage database users and their permissions.

c) User Defined Function to Calculate Workers’ Pay (6 Marks)

php
Copy code
<?php
function calculatePay($hoursWorked, $payPerHour) {
return $hoursWorked * $payPerHour;
}

// Example usage
$hours = 40;
$rate = 200;
$pay = calculatePay($hours, $rate);
echo "Total Pay: Kshs $pay";
?>

d) PHP Code with Switch Case for Days of the Week (8 Marks)
HTML Form:

html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Day of the Week</title>
</head>
<body>
<form action="day_of_week.php" method="post">
<label for="number">Enter a number (1-7):</label><br>
<input type="number" id="number" name="number"><br>
<input type="submit" value="Get Day">
</form>
</body>
</html>

PHP Code:

php
Copy code
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$number = $_POST['number'];

switch ($number) {
case 1:
$day = "Monday";
break;
case 2:
$day = "Tuesday";
break;
case 3:
$day = "Wednesday";
break;
case 4:
$day = "Thursday";
break;
case 5:
$day = "Friday";
break;
case 6:
$day = "Saturday";
break;
case 7:
$day = "Sunday";
break;
default:
$day = "Invalid number";
}

echo "Day: $day";


}
?>
QUESTION FOUR

a) Client-Side vs. Server-Side Form Validation (4 Marks)

 Client-Side Validation: Performed in the user's browser using JavaScript before


submitting the form. Ensures quicker feedback to the user but can be bypassed if
JavaScript is disabled.
 Server-Side Validation: Performed on the server after the form is submitted. Provides
more secure validation as it cannot be bypassed by the client.

b) PHP Code to Validate Non-Empty Fields Before Submission (5 Marks)

HTML Form:

html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<script>
function validateForm() {
var x = document.forms["myForm"]["fieldname"].value;
if (x == "") {
alert("Field cannot be empty");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="submit.php" onsubmit="return validateForm()"
method="post">
<label for="fieldname">Field Name:</label><br>
<input type="text" id="fieldname" name="fieldname"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

PHP Code:

php
Copy code
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fieldname"])) {
echo "Field cannot be empty";
} else {
echo "Form submitted successfully";
}
}
?>
c) MySQL Database Operations (13 Marks)

i. Insert Statement for First Record (5 Marks):

sql
Copy code
INSERT INTO Customers (CustID, Names, Address, Product, OrderValue)
VALUES ('C001', 'Alex Were', 'Nairobi', 'Computers', 150000);

ii. Retrieve Customers Who Ordered Computers (3 Marks):

sql
Copy code
SELECT * FROM Customers WHERE Product = 'Computers';

iii. Delete Customers from Kisumu (5 Marks):

sql
Copy code
DELETE FROM Customers WHERE Address = 'Kisumu';

QUESTION FIVE

a) Web Server Definition (2 Marks)

A web server is a software application that serves web pages to users over the internet or an
intranet. It handles requests from clients (browsers) and responds by sending the requested web
content, such as HTML pages, images, and other resources.

b) Examples of Web Server Software (3 Marks)

1. Apache HTTP Server


2. Nginx
3. Microsoft Internet Information Services (IIS)

c) Advantages of Dynamic Websites Over Static Websites (6 Marks)

1. Interactivity: Dynamic websites allow user interaction and can provide personalized
content based on user input.
2. Content Management: Easier to manage and update content as changes can be made
dynamically through a content management system (CMS).
3. Functionality: Can integrate with databases and other systems to provide features like
user login, e-commerce, and data-driven content.

d) PHP Form for Hotel Booking and Code for Processing (11 Marks)

i. PHP Form for Booking (4 Marks):


html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Hotel Booking</title>
</head>
<body>
<form action="received.php" method="post">
<label for="guest_names">Guest Names:</label><br>
<input type="text" id="guest_names" name="guest_names"><br>
<label for="gender">Gender:</label><br>
<select id="gender" name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select><br>
<label for="checkin_date">Check-in Date:</label><br>
<input type="date" id="checkin_date" name="checkin_date"><br>
<label for="checkout_date">Check-out Date:</label><br>
<input type="date" id="checkout_date" name="checkout_date"><br>
<label for="room_type">Type of Room:</label><br>
<select id="room_type" name="room_type">
<option value="single">Single</option>
<option value="double">Double</option>
<option value="master">Master</option>
</select><br>
<input type="submit" value="Book">
</form>
</body>
</html>

ii. PHP Code for Processing Booking Form (7 Marks):

php
Copy code
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$guest_names = $_POST['guest_names'];
$gender = $_POST['gender'];
$checkin_date = $_POST['checkin_date'];
$checkout_date = $_POST['checkout_date'];
$room_type = $_POST['room_type'];

echo "Guest Names: $guest_names<br>";


echo "Gender: $gender<br>";
echo "Check-in Date: $checkin_date<br>";
echo "Check-out Date: $checkout_date<br>";
echo "Room Type: $room_type<br>";
}
?>
4o
QUESTION ONE

a) "PHP is server-side scripting language." Explain the statement. (2 Marks)

The statement "PHP is a server-side scripting language" means that PHP code is executed on the
server before the resulting HTML is sent to the client's web browser. Unlike client-side
languages (such as JavaScript) which run on the user's machine, PHP scripts are processed by the
web server, which then sends the output (usually HTML) to the client. This allows for dynamic
content generation, database interaction, and other server-side operations.

b) Four Capabilities of PHP Language (4 Marks)

1. Database Integration: PHP can connect to various database systems, such as MySQL,
PostgreSQL, and SQLite, allowing for the creation and manipulation of database records.
2. Server-Side Processing: PHP can handle server-side tasks like file manipulation,
sending emails, and handling form submissions, providing a robust backend for web
applications.
3. Session Management: PHP supports session management, enabling the creation of
personalized user experiences by storing user data across multiple pages.
4. Interoperability: PHP can interact with various web services and APIs, making it
possible to integrate with third-party services, fetch external data, and enhance web
applications with additional functionalities.

c) PHP Code to Demonstrate Connection to MySQL Database Server (5 Marks)

php
Copy code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database_name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "Connected successfully";
}
?>

d) Five Reasons Why MySQL is Popularly Used with Web Applications (5 Marks)

1. Open Source: MySQL is open-source and free to use, making it a cost-effective choice
for developers and businesses.
2. Performance: MySQL is known for its high performance, reliability, and scalability,
handling large volumes of data and high traffic efficiently.
3. Compatibility: MySQL works well with various programming languages (including
PHP) and operating systems, making it versatile for different web applications.
4. Security: MySQL offers robust security features, including user authentication, data
encryption, and secure connections, protecting sensitive data.
5. Community Support: MySQL has a large, active community providing extensive
documentation, tutorials, and support, helping developers solve issues and learn best
practices.

e) MySQL Database Operations (14 Marks)

i. Web Form to Capture Records (4 Marks)

HTML Form:

html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Contact Form</title>
</head>
<body>
<form action="insert_contact.php" method="post">
<label for="id">ID:</label><br>
<input type="text" id="id" name="id"><br>
<label for="surname">Surname:</label><br>
<input type="text" id="surname" name="surname"><br>
<label for="address">Address:</label><br>
<input type="text" id="address" name="address"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Graphical View of the Form:

makefile
Copy code
ID: [ ]
Surname: [ ]
Address: [ ]
[Submit]

ii. PHP Code to Receive and Insert Data from the Form (6 Marks)

php
Copy code
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$id = $_POST['id'];
$surname = $_POST['surname'];
$address = $_POST['address'];

// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database_name";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Insert data into the contacts table


$sql = "INSERT INTO contacts (ID, Surname, Address) VALUES ('$id',
'$surname', '$address')";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
}
?>

iii. PHP Code for Deleting Torich Record from the Table (4 Marks)

php
Copy code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database_name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Delete Torich record from the contacts table


$sql = "DELETE FROM contacts WHERE Surname='Torich'";

if ($conn->query($sql) === TRUE) {


echo "Record deleted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

QUESTION TWO

a) Dynamic vs. Static Web Page (4 Marks)

 Static Web Page: A static web page is a simple HTML page that displays the same
content to every visitor. It does not change unless the developer manually updates the
HTML code. Example:

html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Static Page</title>
</head>
<body>
<h1>Welcome to My Website</h1>
<p>This is a static page.</p>
</body>
</html>

 Dynamic Web Page: A dynamic web page is generated by a server-side script (like PHP)
and can display different content based on user interactions, database queries, or other
variables. Example:

php
Copy code
<?php
$name = "John";
?>
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Page</title>
</head>
<body>
<h1>Welcome, <?php echo $name; ?>!</h1>
<p>This is a dynamic page.</p>
</body>
</html>

b) Loop Program Explanation and Output (4 Marks)

i. Explanation and Output of the Program:

php
Copy code
<?php
$i = 0;
$sum = 0;
while ($i <= 9) {
echo $i . "<br>";
$i++;
$sum += $i;
}
echo "sum=" . $sum . "<br>";
?>

 Explanation: The program initializes two variables, $i and $sum, to 0. It then enters a
while loop that runs as long as $i is less than or equal to 9. In each iteration, it prints the
current value of $i, increments $i by 1, and adds the new value of $i to $sum. Finally, it
prints the total sum.
 Output:

php
Copy code
0<br>
1<br>
2<br>
3<br>
4<br>
5<br>
6<br>
7<br>
8<br>
9<br>
sum=55<br>

ii. Rewrite the Program Using For Loop:

php
Copy code
<?php
$sum = 0;
for ($i = 0; $i <= 9; $i++) {
echo $i . "<br>";
$sum += $i + 1;
}
echo "sum=" . $sum . "<br>";
?>

c) MySQL UPDATE Statement Implementation in PHP (4 Marks)

php
Copy code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database_name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Update statement
$sql = "UPDATE contacts SET Address='New Address' WHERE ID=112";

if ($conn->query($sql) === TRUE) {


echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

$conn->close();
?>

d) Output Statement for Given Variables (3 Marks)

php
Copy code
<?php
$fname = "John";
$county = "Nairobi";
echo "My first Name is $fname and $county is my home county";
?>

Output:

csharp
Copy code
My first Name is John and Nairobi is my home county

QUESTION THREE

a) Switch Case Program for Course Codes (6 Marks)

i. Using Switch Case:

php
Copy code
<?php
$courseCode = "BA";

switch ($courseCode) {
case "BED":
echo "Bachelor of Education";
break;
case "BIT":
echo "Bachelor of Information Technology";
break;
case "BCOM":
echo "Bachelor of Commerce";
break;
case "BA":
echo "Bachelor of Arts";
break;
default:
echo "Invalid Course Code";
}
?>

ii. Using IF Statement:

php
Copy code
<?php
$courseCode = "BA";

if ($courseCode == "BED") {
echo "Bachelor of Education";
} elseif ($courseCode == "BIT") {
echo "Bachelor of Information Technology";
} elseif ($courseCode == "BCOM") {
echo "Bachelor of Commerce";
} elseif ($courseCode == "BA") {
echo "Bachelor of Arts";
} else {
echo "Invalid Course Code";
}
?>

b) Definition of Function (2 Marks)

A function in programming is a block of code designed to perform a specific task. It can be


called multiple times within a program to execute that task whenever needed, promoting code
reusability and modularity.

c) Explanation and Usage of Functions (6 Marks)

i. mysqli_select_db(): This function selects the default database to be used for SQL
operations. Example:

php
Copy code
$conn = mysqli_connect("localhost", "username", "password");
mysqli_select_db($conn, "database_name");

ii. mysqli_fetch_array(): This function fetches a result row as an associative array, a numeric
array, or both. Example:

php
Copy code
$result = mysqli_query($conn, "SELECT * FROM table_name");
while ($row = mysqli_fetch_array($result)) {
echo $row['column_name'];
}

QUESTION FOUR

a) mail() Function in PHP (10 Marks)

i. Various mail() Function Arguments:

 to: The recipient's email address.


 subject: The subject of the email.
 message: The body of the email.
 headers: Additional headers, like "From", "CC", "BCC".

ii. Example Code Demonstrating mail() Function:

php
Copy code
<?php
$to = "[email protected]";
$subject = "Test Email";
$message = "This is a test email sent from PHP.";
$headers = "From: [email protected]";

if (mail($to, $subject, $message, $headers)) {


echo "Email sent successfully.";
} else {
echo "Failed to send email.";
}
?>

b) Variable Scope in PHP (8 Marks)

i. Explanation of Variable Scope: Variable scope refers to the context within which a variable
is accessible in a program. PHP supports local, global, and static scopes.

ii. Two Major Types of Variable Scopes with Examples:

1. Local Scope: Variables declared within a function are local to that function.

php
Copy code
<?php
function localVariable() {
$var = "I am local";
echo $var;
}
localVariable(); // Output: I am local
// echo $var; // Error: Undefined variable
?>

2. Global Scope: Variables declared outside any function have a global scope and can be
accessed anywhere outside functions.

php
Copy code
<?php
$var = "I am global";

function globalVariable() {
global $var;
echo $var;
}

globalVariable(); // Output: I am global


?>

c) Role of Web Server in Web Applications (2 Marks)

A web server hosts web applications, handles HTTP requests from clients (browsers), processes
these requests (sometimes by running scripts), and serves the appropriate web pages or data to
the clients.

QUESTION FIVE

a) PHP Function to Compute Product of Three Integers (6 Marks)

php
Copy code
<?php
function computeProduct($a, $b, $c) {
return $a * $b * $c;
}

$result = computeProduct(2, 3, 4);


echo "The product is: " . $result;
?>

b) PHP Code to Check Login Details from MySQL Table (6 Marks)

php
Copy code
<?php
$username = $_POST['username'];
$password = $_POST['password'];

$conn = new mysqli("localhost", "root", "", "database_name");

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM tbl_users WHERE username='$username' AND
password='$password'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
echo "Login successful";
} else {
echo "Invalid username or password";
}

$conn->close();
?>

c) Four Rules for Naming Variables in PHP (4 Marks)

1. Start with a Letter or Underscore: Variable names must start with a letter or an
underscore (_).
2. Case Sensitive: Variable names are case-sensitive ($Var and $var are different).
3. No Spaces: Variable names cannot contain spaces. Use underscores or camelCase for
readability.
4. No Special Characters: Only letters, numbers, and underscores are allowed.

d) Declare and Initialize Array in PHP (4 Marks)

php
Copy code
<?php
// Indexed array
$fruits = array("Apple", "Banana", "Cherry");

// Associative array
$age = array("Peter" => 35, "Ben" => 37, "Joe" => 43);

// Output array values


echo $fruits[0]; // Output: Apple
echo $age['Peter']; // Output: 35
?>
4o

4o

You might also like