📅 Week 11 - Day 2: PHP-MySQL Connection

Wednesday | Duration: 3 hours

🎯 Learning Objectives

🔗 Database Connection Methods

Method Description Recommended?
MySQLi MySQL Improved extension ✅ Yes (procedural or OOP)
PDO PHP Data Objects (works with multiple databases) ✅ Yes (most flexible)
mysql_* Old MySQL extension ❌ No (deprecated, removed in PHP 7)

🔌 MySQLi Connection (Procedural)

<?php // Database credentials $host = "localhost"; $username = "root"; $password = ""; $database = "school_db"; // Create connection $conn = mysqli_connect($host, $username, $password, $database); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully!"; // Close connection when done mysqli_close($conn); ?>

📁 Database Configuration File

<?php // config.php - Save database connection settings $host = "localhost"; $username = "root"; $password = ""; $database = "school_db"; // Create connection $conn = mysqli_connect($host, $username, $password, $database); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Optional: Set charset to UTF-8 mysqli_set_charset($conn, "utf8mb4"); ?>

📥 Inserting Data from PHP

Method 1: Simple Query (Not Secure)

<?php require_once 'config.php'; $name = "Ahmad Ibrahim"; $email = "ahmad@email.com"; $age = 20; $course = "Web Development"; // Create SQL query $sql = "INSERT INTO students (name, email, age, course) VALUES ('$name', '$email', $age, '$course')"; // Execute query if (mysqli_query($conn, $sql)) { echo "New student added successfully!"; } else { echo "Error: " . mysqli_error($conn); } mysqli_close($conn); ?>

Method 2: Prepared Statements (Secure ✅)

<?php require_once 'config.php'; $name = "Ahmad Ibrahim"; $email = "ahmad@email.com"; $age = 20; $course = "Web Development"; // Prepare statement $stmt = mysqli_prepare($conn, "INSERT INTO students (name, email, age, course) VALUES (?, ?, ?, ?)"); // Bind parameters (s = string, i = integer) mysqli_stmt_bind_param($stmt, "ssis", $name, $email, $age, $course); // Execute if (mysqli_stmt_execute($stmt)) { echo "New student added successfully!"; echo "New ID: " . mysqli_insert_id($conn); } else { echo "Error: " . mysqli_error($conn); } mysqli_stmt_close($stmt); mysqli_close($conn); ?>
Parameter Types in bind_param:
  • s - String
  • i - Integer
  • d - Double/Float
  • b - Blob (binary)

📤 Selecting Data from PHP

Fetch All Records:

<?php require_once 'config.php'; $sql = "SELECT * FROM students"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { echo "<table border='1'>"; echo "<tr><th>ID</th><th>Name</th><th>Email</th><th>Age</th><th>Course</th></tr>"; // Loop through results while ($row = mysqli_fetch_assoc($result)) { echo "<tr>"; echo "<td>" . $row['id'] . "</td>"; echo "<td>" . $row['name'] . "</td>"; echo "<td>" . $row['email'] . "</td>"; echo "<td>" . $row['age'] . "</td>"; echo "<td>" . $row['course'] . "</td>"; echo "</tr>"; } echo "</table>"; } else { echo "No students found."; } mysqli_close($conn); ?>

💻 Complete Registration Form with Database

<!DOCTYPE html> <html> <head> <title>Student Registration</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: Arial, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 20px; } .form-container { max-width: 600px; margin: 50px auto; background: white; padding: 40px; border-radius: 10px; box-shadow: 0 10px 30px rgba(0,0,0,0.3); } h2 { color: #667eea; margin-bottom: 30px; } .form-group { margin-bottom: 20px; } label { display: block; margin-bottom: 5px; font-weight: bold; color: #333; } input, select { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px; } input:focus, select:focus { outline: none; border-color: #667eea; } button { width: 100%; padding: 15px; background: #667eea; color: white; border: none; border-radius: 5px; font-size: 16px; cursor: pointer; } button:hover { background: #5568d3; } .success { background: #d4edda; color: #155724; padding: 15px; border-radius: 5px; margin-bottom: 20px; } .error { background: #f8d7da; color: #721c24; padding: 15px; border-radius: 5px; margin-bottom: 20px; } </style> </head> <body> <div class="form-container"> <h2>Student Registration</h2> <?php require_once 'config.php'; $errors = []; $success = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { // Get and validate inputs $name = trim($_POST['name']); $email = trim($_POST['email']); $age = $_POST['age']; $course = $_POST['course']; // Validation if (empty($name) || strlen($name) < 3) { $errors[] = "Name must be at least 3 characters"; } if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Valid email is required"; } if (empty($age) || $age < 16 || $age > 100) { $errors[] = "Age must be between 16 and 100"; } if (empty($course)) { $errors[] = "Please select a course"; } // Check if email already exists if (empty($errors)) { $checkEmail = mysqli_prepare($conn, "SELECT id FROM students WHERE email = ?"); mysqli_stmt_bind_param($checkEmail, "s", $email); mysqli_stmt_execute($checkEmail); mysqli_stmt_store_result($checkEmail); if (mysqli_stmt_num_rows($checkEmail) > 0) { $errors[] = "Email already registered!"; } mysqli_stmt_close($checkEmail); } // If no errors, insert into database if (empty($errors)) { $stmt = mysqli_prepare($conn, "INSERT INTO students (name, email, age, course) VALUES (?, ?, ?, ?)"); mysqli_stmt_bind_param($stmt, "ssis", $name, $email, $age, $course); if (mysqli_stmt_execute($stmt)) { $success = "Registration successful! Student ID: " . mysqli_insert_id($conn); $_POST = []; // Clear form } else { $errors[] = "Registration failed: " . mysqli_error($conn); } mysqli_stmt_close($stmt); } } mysqli_close($conn); ?> <?php if (!empty($errors)): ?> <div class="error"> <ul> <?php foreach ($errors as $error): ?> <li><?php echo htmlspecialchars($error); ?></li> <?php endforeach; ?> </ul> </div> <?php endif; ?> <?php if ($success): ?> <div class="success"> <?php echo htmlspecialchars($success); ?> </div> <?php endif; ?> <form method="POST" action=""> <div class="form-group"> <label>Full Name:</label> <input type="text" name="name" value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ''; ?>" required> </div> <div class="form-group"> <label>Email:</label> <input type="email" name="email" value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>" required> </div> <div class="form-group"> <label>Age:</label> <input type="number" name="age" min="16" max="100" value="<?php echo isset($_POST['age']) ? htmlspecialchars($_POST['age']) : ''; ?>" required> </div> <div class="form-group"> <label>Course:</label> <select name="course" required> <option value="">-- Select Course --</option> <option value="Web Development">Web Development</option> <option value="Data Science">Data Science</option> <option value="UI/UX Design">UI/UX Design</option> <option value="Mobile Development">Mobile Development</option> </select> </div> <button type="submit">Register Student</button> </form> </div> </body> </html>

✏️ Practice Exercises

  1. Create config.php with database connection
  2. Build registration form that saves to database
  3. Create a page to display all registered students
  4. Add email uniqueness validation
  5. Display success/error messages properly

✅ Security Best Practices

✅ Today's Deliverable

← Previous Course Home Next: Day 3 →