Lec-3-Server-Side Programming with PHP MySQL
Lec-3-Server-Side Programming with PHP MySQL
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."
• 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.
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.
• 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).
When you use a XAMPP setup, you are running a "stack" of technologies that work together. This is the architecture
of our server.
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.
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
• 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.
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.
Tasks:
<!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.
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.
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.
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>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>
<input type="checkbox" name="terms_agree" value="yes" required>
I agree to the terms and conditions.
</label>
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.
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") {
$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 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.
}
?>
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.
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>';
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!
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.
<?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);
}
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);
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();
}
}
?>
<!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>
<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();
?>
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.
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!).