Internet Programmingpp
Internet Programmingpp
QUESTION ONE
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";
}
?>
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>
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'];
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
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.
php
Copy code
// This is a single-line comment
# This is another single-line comment
php
Copy code
/*
This is a multi-line comment
that spans multiple lines.
*/
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'];
// Database connection
$servername = "localhost";
$db_username = "root";
$db_password = "";
$dbname = "database_name";
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
?>
php
Copy code
<?php
$items = array("TV", "Phone", "Radio", "DVD", "CD-ROM");
QUESTION THREE
a) phpMyAdmin (2 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";
}
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)
sql
Copy code
INSERT INTO Customers (CustID, Names, Address, Product, OrderValue)
VALUES ('C001', 'Alex Were', 'Nairobi', 'Computers', 150000);
sql
Copy code
SELECT * FROM Customers WHERE Product = 'Computers';
sql
Copy code
DELETE FROM Customers WHERE Address = 'Kisumu';
QUESTION FIVE
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.
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)
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'];
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.
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.
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.
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>
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";
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_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);
}
QUESTION TWO
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>
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>
php
Copy code
<?php
$sum = 0;
for ($i = 0; $i <= 9; $i++) {
echo $i . "<br>";
$sum += $i + 1;
}
echo "sum=" . $sum . "<br>";
?>
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";
$conn->close();
?>
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
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";
}
?>
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";
}
?>
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
php
Copy code
<?php
$to = "[email protected]";
$subject = "Test Email";
$message = "This is a test email sent from PHP.";
$headers = "From: [email protected]";
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.
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;
}
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
php
Copy code
<?php
function computeProduct($a, $b, $c) {
return $a * $b * $c;
}
php
Copy code
<?php
$username = $_POST['username'];
$password = $_POST['password'];
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();
?>
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.
php
Copy code
<?php
// Indexed array
$fruits = array("Apple", "Banana", "Cherry");
// Associative array
$age = array("Peter" => 35, "Ben" => 37, "Joe" => 43);
4o