MySQL is a widely used, open-source relational database management system. PHP and MySQL make a powerful combination for web development, allowing you to create dynamic and data-driven applications. In this lesson, we'll explore how to interact with MySQL databases using PHP, including establishing connections, querying data, and handling results.

Connecting to a MySQL Database

To connect to a MySQL database, you can use the mysqli or PDO extension in PHP. In this lesson, we'll use the mysqli extension.

  1. Establish a database connection:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

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

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
  1. Close the connection:
$conn->close();

Executing SQL Queries

  1. Select data from the database:
$sql = "SELECT id, firstname, lastname FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 results";
}
  1. Insert data into the database:
$sql = "INSERT INTO users (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
  1. Update data in the database:
$sql = "UPDATE users SET email='[email protected]' WHERE id=1";

if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}
  1. Delete data from the database:
$sql = "DELETE FROM users WHERE id=1";

if ($conn->query($sql) === TRUE) {
    echo "Record deleted successfully";
} else {
    echo "Error deleting record: " . $conn->error;
}

Actionable Work:

Practice interacting with a MySQL database using PHP by completing the following exercises:

  1. Create a simple web application that allows users to submit their name and email address through a form. Store the submitted data in a MySQL database.
  2. Display the list of users from the database on a separate page, including their names and email addresses. Add pagination to the list, so that only a limited number of users are displayed per page.