Home PHP & Databases

PHP Fundamentals & Databases

Take your skills to the next level. Let's learn the essentials of connecting PHP to a MySQL database, SELECTING records, and INSERTING new ones seamlessly.

1. Connecting to the Database

Unlike HTML or CSS, PHP requires a backend server (like XAMPP's Apache) and a database (like MySQL). To communicate with the database, we use the `mysqli` component.

💡 Exam Tip: PHP executed database connections must supply a hostname (usually localhost), a username (default is root for local servers), a password, and the target database name.
Connecting via mysqli
<?php
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'codepath_db';

// Establish connection
$conn = new mysqli($host, $username, $password, $dbname);

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

2. Fetching Data with SELECT FROM

To read data from a table, we use the SELECT statement. The FROM keyword specifies which table, and ORDER BY helps us sort.

💡 Exam Tip: The SELECT * command fetches all columns. You run the query via $conn->query($sql) and then loop through the results checking num_rows > 0.
Fetching records
<?php
$sql = "SELECT * FROM reviews ORDER BY created_at DESC";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Name: " . $row['name'];
    }
} else {
    echo "0 results";
}
?>

3. Saving Data with INSERT INTO

Adding new data to a table involves INSERT INTO. We define the columns we are inserting to and provide the VALUES. It is crucial to escape strings properly to prevent SQL injections.

💡 Exam Tip: Always use $conn->real_escape_string() (or prepared statements) when taking user input from $_POST to save into a database securely.
Inserting a record
<?php
$name = $conn->real_escape_string($_POST['name']);
$comment = $conn->real_escape_string($_POST['comment']);

$sql = "INSERT INTO reviews (name, comment) VALUES ('$name', '$comment')";
$conn->query($sql);
?>

4. Live Example: Interactive Review System UI

Using the principles of CONNECT, INSERT, and SELECT we just learned, you would build HTML interfaces that POST to the PHP backend.

Leave a Course Review

💡 Exam Tip: The form logic visually collects data and sends a POST request. The PHP backend receives this data via the $_POST superglobal variable array to then use an INSERT INTO database command.

Recent Reviews Example

⭐⭐⭐⭐⭐
Alice Walker
April 28, 2026

I loved learning about PHP backend logic! The SELECT and INSERT commands make sense now.

⭐⭐⭐⭐
Mark S.
April 25, 2026

Really solid examples explaining how to structure databases.

← Previous JavaScript