PHP and MySQLi Tutorial

Part 1: Introduction

Welcome! PHP (Hypertext Preprocessor) is a titan of the web. It's a server-side scripting language that powers a huge portion of the internet, including giants like WordPress and Facebook. Its simplicity, flexibility, and vast community support make it an excellent choice for building dynamic web applications.

This tutorial will guide you through the essential concepts of PHP and then show you how to connect to and interact with a MySQL database using the powerful MySQLi extension. By the end, you'll have a solid foundation to start building your own database-driven websites.

Part 2: Top 15 PHP Concepts

Variables are containers for storing information. In PHP, a variable starts with the $ sign, followed by the name of the variable. PHP supports String, Integer, Float, Boolean, Array, Object, and NULL data types.

<?php
$name = "Alice";      // String
$age = 30;            // Integer
$height = 5.8;        // Float
$isStudent = true;    // Boolean
$hobbies = ["reading", "hiking"]; // Array
// var_dump() shows the type and value
var_dump($name);
var_dump($age);
?>

Operators are used to perform operations on variables and values. Common types include Arithmetic (+, -, *, /), Assignment (=, +=), Comparison (==, ===, !=), and Logical (&&, ||, !).

<?php
$x = 10;
$y = 5;

// Arithmetic
echo $x + $y; // 15

// Comparison
var_dump($x > $y); // bool(true)

// Logical
$isLoggedIn = true;
$hasPermission = false;
var_dump($isLoggedIn && $hasPermission); // bool(false)
?>

Conditional statements allow you to perform different actions based on different conditions. if, elseif, and else are the primary tools for this.

<?php
$grade = 85;

if ($grade >= 90) {
    echo "Excellent!";
} elseif ($grade >= 75) {
    echo "Good job!";
} else {
    echo "Please review the material.";
}
?>

Loops are used to execute the same block of code a specified number of times or while a certain condition is true. Types include for, while, do-while, and foreach (for arrays).

<?php
// for loop
for ($i = 1; $i <= 3; $i++) {
    echo "Number $i <br>";
}

// foreach loop
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
    echo "$color <br>";
}
?>

A function is a block of code that can be reused multiple times. You can define your own functions to perform specific tasks.

<?php
function greetUser($name) {
    return "Hello, " . $name . "!";
}

echo greetUser("Bob"); // Outputs: Hello, Bob!
?>

Arrays store multiple values in one single variable. PHP supports indexed arrays (numeric keys), associative arrays (named keys), and multidimensional arrays (arrays containing other arrays).

<?php
// Indexed array
$cars = ["Volvo", "BMW", "Toyota"];
echo $cars[1]; // BMW

// Associative array
$user = [
    "name" => "John Doe",
    "email" => "john@example.com"
];
echo $user["email"]; // john@example.com
?>

Superglobals are built-in variables that are always available in all scopes. They provide information about the request and server environment.

  • $_GET: Contains data sent in the URL query string.
  • $_POST: Contains data sent via an HTTP POST request (e.g., from a form).
  • $_SERVER: Contains information about the server and execution environment.
  • $_SESSION: Contains session variables.
  • $_COOKIE: Contains HTTP cookies.
<?php
// If URL is example.com?name=David
echo $_GET['name']; // Outputs: David

// Shows the server's host name
echo $_SERVER['HTTP_HOST'];
?>

PHP is excellent at handling HTML forms. You can collect data from form fields using the $_GET or $_POST superglobals, depending on the form's `method` attribute.

<!-- HTML Form -->
<form action="process.php" method="post">
    Name: <input type="text" name="username">
    <input type="submit">
</form>

<?php
// In process.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Collect and sanitize the input
    $name = htmlspecialchars($_POST['username']);
    echo "Hello, " . $name;
}
?>

PHP has a rich set of functions for working with strings.

<?php
$sentence = "The quick brown fox";

// Get string length
echo strlen($sentence); // 19

// Find position of a word
echo strpos($sentence, "brown"); // 10

// Replace text
echo str_replace("fox", "dog", $sentence); // The quick brown dog
?>

PHP can create, read, write to, and close files on the server.

<?php
$file = 'data.txt';

// Write to a file (will create if it doesn't exist)
file_put_contents($file, "Hello World!");

// Read from a file
$content = file_get_contents($file);
echo $content; // Hello World!
?>

Basic error handling can be done with the die() or exit() functions, which stop script execution and display a message. This is often used for critical errors, like a failed database connection.

<?php
$file = 'non_existent_file.txt';
$handle = fopen($file, 'r') or die("Could not open file!");

// More advanced error handling uses try...catch blocks
// for exceptions, which is common in modern PHP.
?>

You can include the content of one PHP file into another. require will produce a fatal error and stop the script if the file is not found, while include will only produce a warning and continue.

<!-- In index.php -->
<?php
// Use require for essential files like database connections.
require 'config.php'; 

// Use include for non-critical templates.
include 'header.php'; 
?>

OOP allows you to structure your code around objects. A class is a blueprint for objects, and an object is an instance of a class. Classes have properties (variables) and methods (functions).

<?php
class Car {
    // Property
    public $color;

    // Method
    public function startEngine() {
        return "Engine started!";
    }
}

// Create an object
$myCar = new Car();
$myCar->color = "red";

echo $myCar->color; // red
echo $myCar->startEngine(); // Engine started!
?>

Cookies are stored on the user's browser, while Sessions are stored on the server. They are both used to store user information across multiple page visits, like login status.

<?php
// Start a session (must be at the very top of the script)
session_start();

// Set a session variable
$_SESSION["username"] = "admin";

// Access it on another page
echo "Welcome, " . $_SESSION["username"];

// Set a cookie that expires in 1 hour
setcookie("user_preference", "dark_mode", time() + 3600);
?>

The date() function is used to format a date and/or a time.

<?php
// Set the default timezone to avoid warnings
date_default_timezone_set('America/New_York');

// Y for 4-digit year, m for month, d for day
echo "Today is " . date("Y-m-d") . "<br>";

// h:i:s a for hours, minutes, seconds, and am/pm
echo "The time is " . date("h:i:s a");
?>

Part 3: Top 5 PHP MySQLi Concepts

To interact with a database, you must first establish a connection. The MySQLi extension provides an object-oriented way to do this. You need the server name, username, password, and database name.

<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

Once connected, you can execute SQL queries using the query() method. For queries that return data (like SELECT), it returns a result object. For others (INSERT, UPDATE), it returns true on success or false on failure.

<?php
// Assumes $conn is an active connection object
$sql = "SELECT id, firstname, lastname FROM Guests";
$result = $conn->query($sql);

if ($result) {
    echo "Query executed successfully!";
} else {
    echo "Error: " . $conn->error;
}
?>

After a SELECT query, you need to fetch the data from the result object. The most common method is fetch_assoc(), which returns one row at a time as an associative array.

<?php
// Assumes $result is a valid result object
if ($result->num_rows > 0) {
    // Loop through each row
    while($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"] . " - Name: " . $row["firstname"] . "<br>";
    }
} else {
    echo "0 results found";
}
?>

Prepared statements are a crucial security feature. They prevent SQL injection attacks by separating the SQL command from the data. You use placeholders (?) for data, which is later bound to the query.

<?php
// Prepare the statement
$stmt = $conn->prepare("INSERT INTO Guests (firstname, email) VALUES (?, ?)");

// Bind parameters: 'ss' means two strings
$stmt->bind_param("ss", $firstname, $email);

// Set parameters and execute
$firstname = "Mary";
$email = "mary@example.com";
$stmt->execute();

echo "New record created successfully";

$stmt->close();
?>

It's good practice to close the database connection when you're finished with it to free up resources.

<?php
// Assumes $conn is an active connection object
$conn->close();
echo "Connection closed.";
?>

Part 4: Worked Example: Reading and Displaying Data

This complete example connects to a database, retrieves user data, and displays it in an HTML table. This code would run on a web server with PHP and a MySQL database set up.

<!DOCTYPE html>
<html>
<head>
    <title>User List</title>
    <!-- (Add your table styles here) -->
</head>
<body>

<h1>Registered Users</h1>

<?php
// -- 1. Database Credentials (replace with your own) --
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "my_app_db";

// -- 2. Create and Check Connection --
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("<p>Connection failed: " . $conn->connect_error . "</p>");
}

// -- 3. Define the SQL Query --
// Selects all users from a 'users' table.
$sql = "SELECT id, name, email FROM users ORDER BY name ASC";

// -- 4. Execute the Query --
$result = $conn->query($sql);

// -- 5. Process and Display the Results --
if ($result->num_rows > 0) {
    // If we have results, create the table structure
    echo "<table>";
    echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";
    
    // Loop through each row of the result set
    while($row = $result->fetch_assoc()) {
        // Output each user's data in a table row
        echo "<tr>";
        echo "<td>" . htmlspecialchars($row['id']) . "</td>";
        echo "<td>" . htmlspecialchars($row['name']) . "</td>";
        echo "<td>" . htmlspecialchars($row['email']) . "</td>";
        echo "</tr>";
    }
    
    echo "</table>";
} else {
    // If no users were found in the database
    echo "<p>No users found.</p>";
}

// -- 6. Close the Database Connection --
$conn->close();
?>

</body>
</html>