0% found this document useful (0 votes)
17 views

Section Two Nswer Sheet

Uploaded by

Esubalew
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Section Two Nswer Sheet

Uploaded by

Esubalew
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Practice Answer Sheet

Task 1: Creating a database and a table.

CREATE DATABASE IF NOT EXISTS cocdb;

USE cocdb;

CREATE TABLE IF NOT EXISTS contacts (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(255) NOT NULL,

email VARCHAR(255) NOT NULL,

phone VARCHAR(20),

message TEXT,

submission_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);

Task 2: connecting the web application to the database

 Write a PHP script to connect your “cocdb” database into your web application. And save
this file named as “db.php” in your working folder.
 Your db.php file must display a message that your database is successfully connected.

<?php
// Connection to MySQL
$servername = "localhost";
$username = "root";
$password = "12345";
$dbname = "cocdb";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "DB is Successfully connected";
$conn->close();
?>

1
Task 3: creating the HTML, PHP, and CSS files for the form

 Create as“index.html” file that handles a web pages for linking to database.
 Create “styles.css” file for styling the web pages.
 Create a “process_form.php” files. This file helps to handle form submission and
database insertion.
 Run the “index.html” file and display the output.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Contact Form</title>
</head>
<body>

<div class="container">
<form action="process_form.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>

<label for="email">Email:</label>
<input type="email" id="email" name="email" required>

<label for="phone">Phone:</label>
<input type="tel" id="phone" name="phone">

<label for="message">Message:</label>
<textarea id="message" name="message" rows="4" required></textarea>

<input type="submit" value="Submit">


</form>
</div>

</body>
</html>
styles.css
body {

2
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}

.container {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

form {
display: flex;
flex-direction: column;
}

label {
margin-bottom: 8px;
}

input, textarea {
padding: 10px;
margin-bottom: 16px;
border: 1px solid #ccc;
border-radius: 4px;
}

input[type="submit"] {
background-color: #4caf50;
color: #fff;
cursor: pointer;
}
process_form.php
<?php
// Include the database connection
include 'db.php';
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

3
// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$message = $_POST["message"];

// Insert data into the database


$sql = "INSERT INTO contacts (name, email, phone, message) VALUES ('$name', '$email',
'$phone', '$message')";

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


echo "Form submitted successfully!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}

// Close the database connection


$conn->close();
?>

 Run the “index.html” file and display the output.

4
After the submission the data is inserted, Your database store some records

Unit Two: Retrieve Data from Database and Display on Web Pages in an HTML table
Task 1: Retrieve Data from Database and Display on Web Pages.
 Create a PHP script named as “display_data.php”. This file can retrieves data based on the
search term and displays it in an HTML table.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Display Data</title>
</head>
<body>
<div class="container">
<h2>Data Display</h2>
<!-- Search Form -->
<form action="" method="post">
<label for="search_term">Search:</label>
<input type="text" id="search_term" name="search_term">

5
<button type="submit">Search</button>
</form>
<?php
// Database connection
$host = "localhost";
$username = "root";
$password = "12345";
$database = "cocdb";

$conn = new mysqli($host, $username, $password, $database);


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve data based on user input
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$searchTerm = $_POST["search_term"];
$sql = "SELECT * FROM contacts WHERE
name LIKE '%$searchTerm%' OR
email LIKE '%$searchTerm%' OR
phone LIKE '%$searchTerm%' OR
message LIKE '%$searchTerm%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table border='1'>;
echo“<tr><th>ID</th><th>Name</th><th>Email</th><th>Phone</th><th>Message</
th><th>submission_date</th></tr>";

while ($row = $result->fetch_assoc()) {


echo "<tr>";
echo "<td>" . $row["id"] . "</td>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>" . $row["email"] . "</td>";
echo "<td>" . $row["phone"] . "</td>";
echo "<td>" . $row["message"] . "</td>";
echo "<td>" . $row["submission_date"] . "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "No records found";

6
}
}
$conn->close();
?>
</div>
</body>
</html>
 Run the “display_data.php” files and Display the data in an HTML table format

Now a search form with a text input will displayed. So in our contacts table we have those
attributes: id, name, email, phone, message and submission_date. Then search records by
name. As an example we have Alemu Abebe and click “search” button then look the output.

Data is displayed on Web Pages in an HTML table format.

7
Unit Three: Update Database Data from User Input

Task 1: Creating an update form and an update_process PHP file

 Create an update form and a PHP script to handle the update process, named as
“update_form.php”.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Update Form</title>
</head>
<body>
<div class="container">
<h2>Update Data</h2>
<?php
// Database connection
$host = "localhost";
$username = "root";
$password = "12345";
$database = "cocdb";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

8
// Check if record ID is provided
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
$id = $_GET['id'];
// Retrieve existing data based on ID
$sql = "SELECT * FROM contacts WHERE id = $id";
$result = $conn->query($sql);
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
// Display the update form with existing data
echo "<form action='update_process.php' method='post'>";
echo "<input type='hidden' name='id' value='" . $row['id'] . "'>";
echo "<label for='name'>Name:</label>";
echo "<input type='text' id='name' name='name' value='" . $row['name'] . "' required>";
echo "<label for='email'>Email:</label>";
echo "<input type='email' id='email' name='email' value='" . $row['email'] . "' required>";
echo "<label for='phone'>Phone:</label>";
echo "<input type='tel' id='phone' name='phone' value='" . $row['phone'] . "' required>";
echo "<label for='message'>Message:</label>";
echo "<textarea id='message' name='message' rows='4' required>" . $row['message'] .
"</textarea>";
echo "<button type='submit'>Update</button>";
echo "</form>";
} else {
echo "Record not found";
}
} else {
echo "Invalid record ID";
}
$conn->close();
?>
</div>
</body>
</html>

 Create an updated process PHP Script named as “update_process.php”.

<?php
// Database connection
$host = "localhost";
$username = "root";
$password = "12345";
$database = "cocdb";
$conn = new mysqli($host, $username, $password, $database);

9
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Update data based on user input
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$id = $_POST["id"];
$name = $_POST["name"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$message = $_POST["message"];
$sql = "UPDATE contacts SET
name = '$name',
email = '$email',
phone = '$phone',
message = '$message'
WHERE id = $id";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
$conn->close();
?>

 Run the “update_form.php” files and Display the output

Example: We have try to update the user whose id=3. localhost/ict_coc/update_form.php?id=3

10
Task 2: Deletion of data in the database using PHP scripts

 Create an update form with delete button and named as: “update_delete_form.php”

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Update_delete Form</title>
</head>
<body>
<div class="container">
<h2>Update Data</h2>
<?php
// Database connection
$host = "localhost";
$username = "root";
$password = "12345";
$database = "cocdb";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Check if record ID is provided
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
$id = $_GET['id'];

11
// Retrieve existing data based on ID
$sql = "SELECT * FROM contacts WHERE id = $id";
$result = $conn->query($sql);

if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
// Display the update form with existing data
echo "<form action='update_process.php' method='post'>";
echo "<input type='hidden' name='id' value='" . $row['id'] . "'>";
echo "<label for='name'>Name:</label>";
echo "<input type='text' id='name' name='name' value='" . $row['name'] . "' required>";
echo "<label for='email'>Email:</label>";
echo "<input type='email' id='email' name='email' value='" . $row['email'] . "' required>";
echo "<label for='phone'>Phone:</label>";
echo "<input type='tel' id='phone' name='phone' value='" . $row['phone'] . "' required>";
echo "<label for='message'>Message:</label>";
echo "<textarea id='message' name='message' rows='4' required>" . $row['message'] .
"</textarea>";
echo "<button type='submit'>Update</button>";
echo "</form>";
// Delete button
echo "<form action='delete_process.php' method='post'>";
echo "<input type='hidden' name='id' value='" . $row['id'] . "'>";
echo "<button type='submit' onclick='return confirm(\"Are you sure you want to delete this
record?\")'>Delete</button>";
echo "</form>";
} else {
echo "Record not found";
}
} else {
echo "Invalid record ID";
}
$conn->close();
?>
</div>
</body>
</html>

 Create the delete process PHP script and named as: “delete_process.php”.

<?php

12
// Database connection
$host = "localhost";
$username = "root";
$password = "12345";
$database = "cocdb";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Delete data based on user input
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$id = $_POST["id"];
$sql = "DELETE FROM contacts WHERE id = $id";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
}
$conn->close();
?>

 Run the “update_delete_form.php” files and Display the output

Example: We have try to delete the user whose id=2. localhost/ict_coc/update_delete_form.php?id=2

13
Project Two: Designing and executing server-side script for dynamic web
pages
Task 1: creating a table
 Creating a table named as: “users” with the following attributes:-
o Username
o Email
Deliverable: The users table can accept and store data inserted in user input form
Task 1: Using the “cocdb” database perform the following questions carefully.
 Create and display ‘Hello, PHP!’ by creating message variable.
 Using arithmetic operators to display the sum of two numbers which is 10+5.
 Create If statement to show welcome message when the user is logged in.
 Create a simple for loop that used to generate unordered list with five list items.
 Create a link to Go to Form and create the following user input form to accept Username
and Email.
 Create “index.php” file.

14
o (NB: This an “index2.php” file must include all tasks of PHP variable,
arithmetic operators, if_statement and for_loop statements)
 Create a “form.php”, this file will display the form for user input.

 Create a “submit_form.php”, this file will handle the form submission and display the
submitted data.
 Access index.php to see the output of all tasks and navigate to the form as shown in the
screenshot below.
 Access the “Go to Form” link then insert and store data into “users” table
Creating users table
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

index2.php

<?php include('db.php'); ?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Sample PHP Project</title>

<style>

header {

background-color: #90ee90; /* light green color */

padding: 10px;

text-align: center;

15
}

footer {

background-color: #f1f1f1;

padding: 10px;

text-align: center;

position: fixed;

width: 100%;

bottom: 0;

</style>

</head>

<body>

<header>

<h1>Sample PHP Project</h1>

</header>

<!-- Task 2 -->

<?php

$message = "<br>Hello, PHP!";

echo $message;

?>

<!-- Task 3 -->

<?php

16
$num1 = 10;

$num2 = 5;

$sum = $num1 + $num2;

echo "<br><br>Sum : $sum";

?>

<!-- Task 4 -->

<h2>Conditional Statement</h2>

<?php

$is_logged_in = true; // Assume the user is logged in for demonstration

if ($is_logged_in) {

echo "Welcome User1";

?>

<!-- Task 5 -->

<h2>For Loop in PHP</h2>

<?php

echo "<ul>";

for ($i = 1; $i <= 5; $i++) {

echo "<li>Item $i</li>";

echo "</ul>";

?>

<!-- Task 6 -->

17
<a href="form.php">Go to Form</a>

<footer>

<p>Prepared by Endale Bereket</p>

</footer>

</body>

</html>

form.php
<?php include('db.php'); ?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>User Input Form</title>

<style>

header {

background-color: #90ee90; /* light green color */

padding: 10px;

text-align: center;

footer {

background-color: #f1f1f1;

padding: 10px;

18
text-align: center;

position: fixed;

width: 100%;

bottom: 0;

</style>

</head>

<body>

<header>

<h1>User Input Form</h1>

</header>

<form action="submit_form.php" method="post">

<label for="username">Username:</label>

<input type="text" id="username" name="username"><br><br>

<label for="email">Email:</label>

<input type="email" id="email" name="email"><br><br>

<input type="submit" value="Submit">

</form>

<br>

<a href="index.php">Go back to Home</a>

<footer>

<p>Prepared by ABC</p>

19
</footer>

</body>

</html>

submit_form.php
<?php
// Include the database connection
include 'db.php';

// Check if the form is submitted


if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form data
$username = mysqli_real_escape_string($conn, $_POST['username']);
$email = mysqli_real_escape_string($conn, $_POST['email']);

// Insert the data into the 'users' table


$sql = "INSERT INTO users (username, email) VALUES ('$username', '$email')";

if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

// Close the database connection


mysqli_close($conn);
} else {
echo "Invalid Request";
}
?>

20

You might also like