0% found this document useful (0 votes)
8 views15 pages

Lec-3-Server-Side Programming with PHP MySQL

The document provides a comparative overview of popular server-side programming languages and their frameworks, highlighting key features, performance, scalability, ecosystem, learning curve, and common use cases. It also includes a comprehensive guide for learning server-side web development using PHP and MySQL, detailing the client-server model, static vs. dynamic websites, and the architecture of a PHP web application. Additionally, it covers setting up a development environment with XAMPP and VS Code, as well as data submission methods and handling HTML forms in PHP.

Uploaded by

mahesh vimukthi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views15 pages

Lec-3-Server-Side Programming with PHP MySQL

The document provides a comparative overview of popular server-side programming languages and their frameworks, highlighting key features, performance, scalability, ecosystem, learning curve, and common use cases. It also includes a comprehensive guide for learning server-side web development using PHP and MySQL, detailing the client-server model, static vs. dynamic websites, and the architecture of a PHP web application. Additionally, it covers setting up a development environment with XAMPP and VS Code, as well as data submission methods and handling HTML forms in PHP.

Uploaded by

mahesh vimukthi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Comparison of Popular Server-Side Languages and

Frameworks
This table provides a comparative overview of popular server-side programming languages and their key
frameworks, drawing information from the "Comprehensive Guide to Server-Side Programming."

Languag Popular Key Features Typical Scalability Ecosystem Learnin Common


e Framewor Performan & g Curve Use Cases
ks ce Communi
ty
JavaScri Express.js, Asynchronous, Good to Excellent Vast (npm) Moderat Real-time
pt NestJS, non-blocking Excellent (especially e apps (chat,
(Node.js) Koa, I/O, event- for I/O- games),
Hapi.js driven, single- bound APIs,
threaded with tasks) microservice
event loop s, SPAs
backends
Python Django, Readability, Moderate to Good (can Large & Easy to Web dev,
Flask, large standard Good be scaled Active Moderat data
FastAPI library, strong with proper e analysis,
data science/ML architecture ML,
integration ) scientific
computing,
automation
Java Spring Platform- Good to Excellent Very Large Moderat Large
Boot, independent Excellent (designed & Mature e to enterprise
Jakarta EE, (WORA), strong for large- Hard apps,
Quarkus, memory scale Android
Micronaut management, systems) backends,
robust, mature big data,
high-
concurrency
systems
Ruby Ruby on Elegant syntax, Moderate Good (with Strong & Moderat Web dev
Rails (RoR) metaprogrammi careful Dedicated e (rapid
ng, "convention design) prototyping
over &
configuration" development
), scripting
PHP Laravel, Large Moderate to Good Very Large Easy to Websites,
Symfony community, easy Good (powers & Active Moderat CMS
to deploy, vast much of the e (WordPress,
amount of web) Drupal), e-
existing commerce,
code/CMSs general web
development
C# ASP.NET Strong typing, Excellent Excellent Large Moderat Enterprise
(.NET) Core excellent (well-suited (Microsoft e apps, web
performance for ) services,
with .NET game dev
Core+, cross- enterprise (Unity),
platform scale) Windows &
cross-
platform
apps
Go Gin, Echo, Concurrency Excellent Excellent Growing Moderat Network
(Golang) (Stdlib (goroutines, (built for Rapidly e services,
net/http) channels), fast concurrent distributed
compilation, systems) systems,
static binaries, microservice
simplicity s, CLIs,
high-
performance
APIs
Scala Play Functional Good to Excellent Moderate Hard High-
Framework, programming, Excellent (for high- & Niche concurrency
Akka HTTP JVM-based, concurrenc systems, big
strong y) data
concurrency processing,
features complex
backend
services
Elixir Phoenix Functional, Excellent Excellent Growing & Moderat Real-time
Framework concurrent (highly Passionate e to apps,
(BEAM VM), scalable Hard distributed
fault-tolerant, and fault- systems,
real-time tolerant) high-
capabilities availability
systems, IoT
Rust Actix, Memory safety Excellent Excellent Growing Hard Systems
Rocket, without garbage (for Rapidly programmin
Axum collection, high performanc g, web
performance, e-critical backends
concurrency systems) requiring
high
performance
& safety,
game
engines

Key Aspects Explained:

• Key Features: Core characteristics that define the language and its common frameworks.
• Typical Performance: General performance expectations. Actual performance depends heavily on the
specific application, framework usage, and optimization.
• Scalability: How well applications built with the language/framework can handle increasing load, both
horizontally (more machines) and vertically (more resources on one machine).
• Ecosystem & Community: The size and activity of the developer community, availability of libraries, tools,
and support.
• Learning Curve: The relative difficulty for a new developer to become proficient.
• Common Use Cases: Typical types of applications and systems where the language/framework excels.
Considerations When Choosing:

• Project Requirements: What are the performance, scalability, and security needs?
• Team Expertise: What languages and frameworks is the team already familiar with?
• Time to Market: Some frameworks (e.g., Ruby on Rails, Django) are known for rapid development.
• Long-term Maintainability: Consider the clarity of the language and the structure imposed by the
framework.
• Specific Problem Domain: Some languages/frameworks are better suited for particular tasks (e.g., Python
for data science, Go for networking).
Server-Side Programming with PHP & MySQL
Welcome! This guide is your comprehensive, step-by-step manual for learning server-side web development. We
will start from the absolute basics and build our way up to creating dynamic, database-driven web applications. Our
toolkit will be PHP, one of the most popular server-side languages, and MySQL, the world's most popular open-
source database. We'll set up a professional development environment on your Windows 11 PC using XAMPP and
VS Code.

Module 1: The Big Picture: How the Web Works


Before we write a single line of code, it's crucial to understand the environment our code will live in.

1.1. The Client-Server Model

At its heart, the web runs on a simple model:

1. The Client: This is the user's web browser (Chrome, Firefox, Edge) on their computer or phone. It requests
information.
2. The Server: This is a powerful computer somewhere in the world that is always on, waiting for requests. It
serves (sends back) information.

When you type www.google.com into your browser (the client), you are sending a request over the internet to one
of Google's servers. The server processes this request and sends back a response, which your browser then renders
as the Google homepage.

1.2. Static vs. Dynamic Websites

• Static Websites: The server just sends back pre-written files (HTML, CSS, JavaScript, images) exactly as
they are stored. The content is the same for every user. Think of it as a restaurant handing every customer the
exact same printed menu.
• Dynamic Websites: This is where PHP comes in. The server doesn't just send a file. It runs a program (our
PHP script) that generates a custom HTML page on the fly. This allows for user logins, personalized content,
search results, social media feeds, etc. Think of this as a restaurant where a chef (PHP) cooks a custom meal
(the webpage) for you based on your order (your request).

1.3. Architecture: The Anatomy of a PHP Web Application

When you use a XAMPP setup, you are running a "stack" of technologies that work together. This is the architecture
of our server.

1. Client (Browser): Requests a .php page (e.g., http://localhost/profile.php).


2. Apache (The Web Server): This is the "front door." Apache receives the request. It sees the .php extension
and knows it shouldn't just send the file. Instead, it hands the file over to the PHP interpreter.
3. PHP (The Processor/Interpreter): This is the "brain." PHP executes the code inside the .php file from top
to bottom. It might perform calculations, handle form data, or, crucially, talk to the database.
4. MySQL (The Database): This is the "long-term memory." If the PHP script needs to retrieve or store
information (like user data, blog posts, product info), it sends a query (a command) to the MySQL database.
MySQL finds or saves the data and sends the result back to PHP.
5. The Response Journey:
o PHP takes the data from the database (if any) and uses it to build a final HTML document as a plain
string of text.
o PHP hands this finished HTML string back to Apache.
o Apache sends the HTML document back to the client's browser as the response.
o The browser receives the pure HTML and renders it for the user to see. The user never sees the PHP
code, only the final HTML output.

This entire process happens in a fraction of a second.

Lab Sheet 1: Conceptual Review

Objective: Solidify your understanding of the core architecture.

Tasks:

1. Draw your own diagram of the client-server model, labeling the Client, Server, Request, and Response.
2. In your own words, explain the difference between a static site and a dynamic site. Provide an example of
each.
3. Write a short paragraph describing the job of each component in the XAMPP stack:
o What does Apache do?
o What is PHP's role?
o What is MySQL used for?
4. If you visit a Facebook profile page, is that a static or dynamic page? Justify your answer by describing what
you think is happening on the server.

Module 2: Setting Up Your Development Environment


Now, let's build our local server on your Windows 11 machine. "Local" means it runs entirely on your PC for
development and testing.

2.1. Installing XAMPP

XAMPP is a free package that installs Apache, MySQL, PHP, and phpMyAdmin (a tool for managing databases) all
at once.

1. Download: Go to the official Apache Friends website and download the latest version of XAMPP for
Windows.
2. Install:
o Run the installer you downloaded.
o You may see a warning about User Account Control (UAC). It's best practice to not install XAMPP
in the default C:\Program Files directory. A good choice is C:\xampp.
o During the component selection, you can leave the defaults checked. The essential components are
Apache, MySQL, and PHP. phpMyAdmin is also highly recommended.
o Complete the installation.
3. The XAMPP Control Panel:
o After installation, launch the XAMPP Control Panel.
o You will see a list of modules. For now, we only need two.
o Click the Start button for Apache. It should highlight green.
o Click the Start button for MySQL. It should also highlight green.
o If they don't start, it's often because another service (like Skype) is using their default port (80 or 443).
The XAMPP logs can help you diagnose this.
4. Verify Installation: Open your web browser and navigate to http://localhost. You should see the
XAMPP dashboard page. This confirms your server is running!
2.2. The htdocs Folder: Your Web Root

This is the most important folder in your XAMPP installation.

• Location: C:\xampp\htdocs
• Purpose: This folder is the "root" of your web server. Any files or folders you put in here can be accessed
through your browser. For example, if you create a folder C:\xampp\htdocs\myproject, you can access it
at http://localhost/myproject.

2.3. Installing and Configuring VS Code

VS Code is our code editor. It's lightweight, powerful, and has great extensions for PHP development.

1. Download & Install: Get it from the official Visual Studio Code website. The installation is straightforward.
2. Essential Extensions: Open VS Code, go to the Extensions view (the square icon on the left sidebar). Search
for and install these:
o PHP Intelephense: This provides intelligent code completion, error checking, and symbol discovery
for PHP. It's a lifesaver.
o Prettier - Code formatter: This helps keep your code neat and consistently formatted.

Lab Sheet 2: Your First "Hello World" PHP Page

Objective: Verify your entire development environment is working correctly.

Tasks:

1. Navigate to your htdocs folder (C:\xampp\htdocs).


2. Create a new folder inside htdocs called learning-php. This will be your main project folder for this guide.
3. Open the learning-php folder in VS Code (File -> Open Folder...).
4. In the VS Code Explorer panel, create a new file named index.php.
5. In this new file, type the following code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First PHP Page</title>
</head>
<body>
<h1>Hello from HTML!</h1>
<p>
<?php
// This is a PHP code block.
// The echo command outputs text to the page.
echo "Hello, World! The server is working!";
?>
</p>
<p>
<?php
echo "Today's date is " . date('Y-m-d') . ".";
?>
</p>
</body>
</html>
6. Save the file.
7. Make sure Apache and MySQL are running in your XAMPP Control Panel.
8. Open your web browser and go to the URL: http://localhost/learning-php/ (or
http://localhost/learning-php/index.php).
9. Verification: You should see a webpage that says "Hello from HTML!", "Hello, World! The server is
working!", and the current date. If you see this, your environment is perfectly set up. If you see the raw code,
it means PHP is not being processed correctly.

Module 3: Data Submission and Processing


Web applications are all about interaction. The most common form of interaction is a user submitting data to the
server for processing.

3.1. How Data is Sent: GET and POST

There are two primary methods for sending data from the client to the server:

• GET Method:
Data is appended to the URL in a "query string."
o
Example: http://example.com/search.php?query=php+tutorial&page=1
o
The data (query=php+tutorial, page=1) is visible in the URL bar, browser history, and server logs.
o
Use Cases: Best for non-sensitive data, like search queries, page numbers, or filter parameters. It's
o
bookmarkable.
o Limitations: The length of a URL is limited (usually around 2000 characters). Not for passwords or
sensitive information.
• POST Method:
o Data is sent in the body of the HTTP request. It is not visible in the URL.
o Use Cases: The standard for submitting forms with sensitive data (passwords, personal info) or large
amounts of data (long text posts).
o More secure than GET because the data isn't exposed in the URL.

3.2. PHP Superglobals: Your Data Mailboxes

PHP automatically collects any data sent to it and places it into special, pre-filled variables called superglobals.
They are available in any scope. The main ones for form data are:

• $_GET: An associative array containing all the data sent via the GET method.
• $_POST: An associative array containing all the data sent via the POST method.
• $_REQUEST: An associative array that contains the contents of $_GET, $_POST, and $_COOKIE. It's generally
better to be specific and use $_GET or $_POST.

Let's say a user submits a form to login.php using the POST method with two fields: username and password. In
login.php, you would access that data like this:

$user = $_POST['username'];
$pass = $_POST['password'];
Module 4: Handling HTML Forms in PHP
This is the most common use case for PHP. Let's build a full example.

4.1. Creating the HTML Form

First, we need the HTML. In your learning-php folder, create a new file named contact.html.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Us</title>
<style>
body { font-family: sans-serif; }
.container { max-width: 600px; margin: 20px auto; padding: 20px; border: 1px solid
#ccc; border-radius: 8px; }
label { display: block; margin-bottom: 5px; }
input, select, textarea { width: 100%; padding: 8px; margin-bottom: 10px; border-
radius: 4px; border: 1px solid #ccc; box-sizing: border-box; }
input[type="radio"], input[type="checkbox"] { width: auto; }
.btn { background-color: #007BFF; color: white; padding: 10px 15px; border: none;
border-radius: 4px; cursor: pointer; }
</style>
</head>
<body>
<div class="container">
<h2>Contact Us</h2>
<!--
action="handle-form.php": Where to send the form data.
method="post": How to send the data (securely).
-->
<form action="handle-form.php" method="post">
<label for="name">Full Name:</label>
<input type="text" id="name" name="customer_name" required>

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


<input type="email" id="email" name="customer_email" required>

<label>Inquiry Type:</label>
<label><input type="radio" name="inquiry_type" value="sales" checked>
Sales</label>
<label><input type="radio" name="inquiry_type" value="support"> Technical
Support</label>
<label><input type="radio" name="inquiry_type" value="billing"> Billing</label>

<label for="subject">Subject:</label>
<select id="subject" name="message_subject">
<option value="general">General Question</option>
<option value="feedback">Website Feedback</option>
<option value="partnership">Partnership Opportunity</option>
</select>

<label>How did you hear about us?</label>


<label><input type="checkbox" name="how_heard[]" value="search"> Search
Engine</label>
<label><input type="checkbox" name="how_heard[]" value="social"> Social
Media</label>
<label><input type="checkbox" name="how_heard[]" value="friend">
Friend/Colleague</label>

<label for="message">Your Message:</label>


<textarea id="message" name="customer_message" rows="6" required></textarea>

<label>
<input type="checkbox" name="terms_agree" value="yes" required>
I agree to the terms and conditions.
</label>

<button type="submit" class="btn">Send Message</button>


</form>
</div>
</body>
</html>

Key Points:

• name attribute: This is CRITICAL. The name attribute of each input becomes the key in the $_POST array in
PHP. name="customer_name" becomes $_POST['customer_name'].
• action attribute: Specifies the PHP file that will process the data.
• method attribute: We use post.
• Checkbox Arrays: Notice name="how_heard[]". The square brackets tell PHP to treat this as an array. This
allows the user to select multiple checkboxes and for us to receive them all.

4.2. The PHP Processing Script

Now, create the file that will do the work: handle-form.php in the same folder.

<?php
// ALWAYS start with this check.
if ($_SERVER["REQUEST_METHOD"] == "POST") {

// --- Part 1: Data Retrieval and Sanitization ---


// Use htmlspecialchars to prevent XSS attacks. This converts characters like < and > to
their HTML entities.
// Use trim() to remove any accidental whitespace from the beginning or end of the input.

$name = trim(htmlspecialchars($_POST['customer_name']));
$email = trim(htmlspecialchars($_POST['customer_email']));
$inquiryType = htmlspecialchars($_POST['inquiry_type']);
$subject = htmlspecialchars($_POST['message_subject']);
$message = trim(htmlspecialchars($_POST['customer_message']));

// For the checkbox array, we need to check if it's set first.


$howHeard = isset($_POST['how_heard']) ? $_POST['how_heard'] : [];
// Sanitize each value in the array
$sanitizedHowHeard = [];
foreach ($howHeard as $source) {
$sanitizedHowHeard[] = htmlspecialchars($source);
}
$howHeardString = implode(', ', $sanitizedHowHeard); // Convert array to a comma-separated
string for easy display.

// For a single checkbox, check if it exists (it's only sent if checked)


$agreedToTerms = isset($_POST['terms_agree']) ? "Yes" : "No";

// --- Part 2: Data Validation (Simple Example) ---


// A real app would have much more robust validation.
$errors = [];
if (empty($name)) {
$errors[] = "Name is required.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "A valid email is required.";
}
if (empty($message)) {
$errors[] = "Message is required.";
}
if ($agreedToTerms === "No") {
$errors[] = "You must agree to the terms.";
}

// --- Part 3: Processing ---


// If there are errors, display them. Otherwise, display the submitted data.
if (!empty($errors)) {
// Redirect back to the form with an error message (more advanced topic)
// For now, we'll just display the errors.
echo "<h2>Error!</h2>";
echo "<ul>";
foreach ($errors as $error) {
echo "<li>$error</li>";
}
echo "</ul>";
echo '<a href="contact.html">Go back to the form</a>';
} else {
// In a real application, you would now:
// 1. Save this data to a database.
// 2. Send an email notification.
// 3. Redirect the user to a "Thank You" page.

// For this lab, we'll just display the data back to the user to confirm.
echo "<!DOCTYPE html><html><head><title>Submission Received</title>";
echo "<style>body { font-family: sans-serif; line-height: 1.6; } .container { max-
width: 600px; margin: 20px auto; padding: 20px; border: 1px solid #ccc; border-radius: 8px;
}</style>";
echo "</head><body><div class='container'>";
echo "<h1>Thank You, " . $name . "!</h1>";
echo "<p>We have received your message and will respond to " . $email . " shortly.</p>";
echo "<h3>Summary of your submission:</h3>";
echo "<ul>";
echo "<li><strong>Name:</strong> " . $name . "</li>";
echo "<li><strong>Email:</strong> " . $email . "</li>";
echo "<li><strong>Inquiry Type:</strong> " . ucfirst($inquiryType) . "</li>";
echo "<li><strong>Subject:</strong> " . $subject . "</li>";
echo "<li><strong>Heard from:</strong> " . $howHeardString . "</li>";
echo "<li><strong>Agreed to Terms:</strong> " . $agreedToTerms . "</li>";
echo "<li><strong>Message:</strong><br>" . nl2br($message) . "</li>";
echo "</ul>";
echo "</div></body></html>";
}

} else {
// If someone tries to access this page directly without POSTing data.
echo "<h1>Access Denied</h1>";
echo "<p>You must submit the form to access this page.</p>";
header('Location: contact.html'); // Redirect them back to the form.
exit(); // Stop script execution.
}
?>

4.3. Security: Validation and Sanitization

This is the most important lesson in this module. NEVER TRUST USER INPUT.
• Sanitization: Cleaning the data before you use it. We did this with trim() and htmlspecialchars().
htmlspecialchars prevents Cross-Site Scripting (XSS), where an attacker tries to inject malicious
JavaScript into your page.
• Validation: Checking if the data is in the correct format after sanitizing. We did this with empty() and
filter_var($email, FILTER_VALIDATE_EMAIL). This ensures we get the data we expect.

Lab Sheet 3 & 4: The Contact Form

Objective: Get hands-on experience with creating and processing an HTML form.

Tasks:

1. Create the contact.html and handle-form.php files as shown above in your learning-php project folder.
2. Open http://localhost/learning-php/contact.html in your browser.
3. Test Case 1 (Happy Path): Fill out the form completely and correctly. Click "Send Message". Verify that
you see the "Thank You" page with all the correct information displayed.
4. Test Case 2 (Validation): Go back to the form. Try submitting it with the name field empty. What happens?
Now try submitting it with an invalid email address (e.g., "[email protected]"). Verify that you see the error
messages.
5. Test Case 3 (Security): Go back to the form. In the "Full Name" field, enter
<script>alert('XSS');</script>. Submit the form.
o Observe the result: The "Thank You" page should display the text
<script>alert('XSS');</script> and NOT execute a JavaScript alert box. This proves
htmlspecialchars() is working and has protected your page.
6. Experiment: Modify the handle-form.php script to display the $_POST array directly at the top to see its
raw structure. Use print_r($_POST); or var_dump($_POST); inside a <pre> tag for readable output. This
is an excellent debugging technique.
7. echo '<pre>';
8. print_r($_POST);
9. echo '</pre>';

Module 5: MySQL and PHP in Action


Now let's connect our PHP application to its long-term memory: the MySQL database. We will build a simple
"Guestbook" application.

5.1. Creating the Database with phpMyAdmin

1. Open the XAMPP Control Panel and click the Admin button on the MySQL row. This will open
phpMyAdmin in your browser.
2. On the left, click New.
3. For the database name, enter guestbook_db and click Create.
4. You will be taken to the "Create table" screen.
o Table Name: entries
o Number of columns: 4
o Click Create.
5. Now, define the structure of your table:
o Column 1:
▪ Name: id
▪ Type: INT
▪ Length/Values: 11
▪ Index: PRIMARY (This makes it the unique identifier for each row)
▪ Check the box for A_I (AUTO_INCREMENT). This means MySQL will automatically
assign a new, unique number to each entry.
o Column 2:
▪ Name: guest_name
▪ Type: VARCHAR (Variable length string)
▪ Length/Values: 100
o Column 3:
▪ Name: message
▪ Type: TEXT (For long text)
o Column 4:
▪ Name: created_at
▪ Type: TIMESTAMP
▪ Default: CURRENT_TIMESTAMP (MySQL will automatically set the time when a row is created)
6. Click Save. Your database and table are now ready!

5.2. CRUD Operations with PHP and MySQLi

CRUD stands for Create, Read, Update, Delete. These are the four fundamental operations of any database
application. We will use the MySQLi (MySQL Improved) extension in PHP.

Let's create one master file for our guestbook: guestbook.php.

<?php
// --- Database Connection ---
$dbHost = 'localhost';
$dbUser = 'root'; // Default XAMPP user
$dbPass = ''; // Default XAMPP password
$dbName = 'guestbook_db';

// Create connection
$conn = new mysqli($dbHost, $dbUser, $dbPass, $dbName);

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

// --- CREATE (Handle Form Submission) ---


$form_error = '';
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit_entry'])) {
$guest_name = trim(htmlspecialchars($_POST['guest_name']));
$message = trim(htmlspecialchars($_POST['message']));

if (empty($guest_name) || empty($message)) {
$form_error = "Both name and message are required.";
} else {
// Use PREPARED STATEMENTS to prevent SQL Injection
$sql = "INSERT INTO entries (guest_name, message) VALUES (?, ?)";
$stmt = $conn->prepare($sql);

// 'ss' means we are binding two strings


$stmt->bind_param("ss", $guest_name, $message);

if ($stmt->execute()) {
// Success! Redirect to the same page to prevent form re-submission on refresh
header("Location: guestbook.php");
exit();
} else {
$form_error = "Error: " . $stmt->error;
}
$stmt->close();
}
}

// --- READ (Fetch all entries to display) ---


$sql_select = "SELECT id, guest_name, message, created_at FROM entries ORDER BY created_at
DESC";
$result = $conn->query($sql_select);

?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Guestbook</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica,
Arial, sans-serif; background-color: #f4f4f9; color: #333; }
.container { max-width: 700px; margin: 40px auto; padding: 20px; background-color:
#fff; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
h1, h2 { text-align: center; color: #0056b3; }
form { margin-bottom: 30px; padding: 20px; border: 1px solid #ddd; border-radius: 8px;
}
label { display: block; margin-bottom: 8px; font-weight: bold; }
input[type="text"], textarea { width: 100%; padding: 10px; margin-bottom: 15px;
border-radius: 4px; border: 1px solid #ccc; box-sizing: border-box; }
button { background-color: #28a745; color: white; padding: 12px 20px; border: none;
border-radius: 4px; cursor: pointer; font-size: 16px; }
.error { color: #dc3545; font-weight: bold; margin-bottom: 15px; }
.entry { border: 1px solid #eee; padding: 15px; margin-bottom: 15px; border-radius:
5px; background-color: #fafafa; }
.entry p { margin: 0; white-space: pre-wrap; word-wrap: break-word; }
.entry-meta { font-size: 0.9em; color: #666; margin-top: 10px; }
</style>
</head>
<body>
<div class="container">
<h1>PHP & MySQL Guestbook</h1>

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


<h2>Sign the Guestbook</h2>
<?php if (!empty($form_error)): ?>
<p class="error"><?php echo $form_error; ?></p>
<?php endif; ?>

<label for="name">Your Name:</label>


<input type="text" id="name" name="guest_name" required>

<label for="message">Your Message:</label>


<textarea id="message" name="message" rows="5" required></textarea>

<button type="submit" name="submit_entry">Submit Entry</button>


</form>

<hr>

<h2>Entries</h2>
<div id="entries-list">
<?php if ($result->num_rows > 0): ?>
<?php while($row = $result->fetch_assoc()): ?>
<div class="entry">
<p><?php echo nl2br($row['message']); ?></p>
<p class="entry-meta">
<strong>- <?php echo $row['guest_name']; ?></strong>
on <?php echo date('F j, Y, g:i a',
strtotime($row['created_at'])); ?>
</p>
</div>
<?php endwhile; ?>
<?php else: ?>
<p>No entries yet. Be the first to sign!</p>
<?php endif; ?>
</div>
</div>
</body>
</html>

<?php
// Close the database connection
$conn->close();
?>

Key Concepts in this script:

1. Connection: We establish a connection to the database at the top. die() stops the script if the connection
fails.
2. Prepared Statements (Security): This is the modern, secure way to run database queries. Instead of putting
variables directly into the SQL string, we use ? as placeholders. We then "bind" the variables to these
placeholders. This makes SQL Injection attacks impossible, as the database engine never confuses user data
with SQL commands.
3. Create: The if ($_SERVER["REQUEST_METHOD"] == "POST") block handles adding a new entry.
4. Read: The $sql_select query fetches all records. We then loop through the $result object using $result-
>fetch_assoc() to display each row.
5. Post/Redirect/Get (PRG) Pattern: After a successful POST submission, we use header("Location:
guestbook.php"); to redirect the user. This is a standard pattern that prevents the same form from being
submitted again if the user refreshes the "Thank You" page.
6. Closing the Connection: It's good practice to close the database connection with $conn->close(); when
you're done with it.

Lab Sheet 5: The Guestbook Application

Objective: Build your first full-stack, database-driven PHP application.

Tasks:

1. Follow the steps in section 5.1 to create the guestbook_db database and the entries table using
phpMyAdmin.
2. Create the guestbook.php file in your learning-php folder and paste the code from section 5.2 into it.
3. Navigate to http://localhost/learning-php/guestbook.php.
4. Test the CREATE operation: Fill out the form with your name and a message. Click "Submit Entry". You
should see your entry appear in the "Entries" list below.
5. Verify in the database: Go back to phpMyAdmin. Click on your entries table. You should see the data
you just submitted stored there.
6. Test the READ operation: Add 2-3 more entries. Verify they all appear on the page, with the newest one at
the top. Refresh the page; the data should persist because it's being read from the database every time.
7. Challenge (Advanced): Can you add a "Delete" button to each entry?
o Hint: The delete button will need to be a link or a form that sends the id of the entry to delete. You
might use a GET request for simplicity: <a href="delete-entry.php?id=<?php echo
$row['id']; ?>">Delete</a>.
o You would then create a delete-entry.php script that connects to the database, gets the ID from
$_GET['id'], and runs a DELETE FROM entries WHERE id = ? query (using a prepared statement!).

You might also like