Executing SQL Queries in PHP

Tutorial 2 of 5

1. Introduction

In this tutorial, we will learn how to execute SQL queries using PHP. This is an essential skill if you want to create, read, update, or delete records in your database through a PHP application.

By the end of this tutorial, you will be able to:
- Connect to a MySQL database using PHP
- Execute various SQL queries using PHP
- Handle errors that may occur during the execution of SQL queries

Prerequisites:
- Basic knowledge of PHP and MySQL
- PHP and MySQL installed on your computer

2. Step-by-Step Guide

First, we need to establish a connection to the database. We will use MySQLi, a PHP extension designed to work with MySQL databases.

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "my_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";
?>

To execute SQL queries, we use the query method of the MySQLi object.

$sql = "YOUR SQL QUERY";
$result = $conn->query($sql);

if ($result === TRUE) {
    echo "Query executed successfully";
} else {
    echo "Error executing query: " . $conn->error;
}

3. Code Examples

Example 1: SELECT Query

Here's how to execute a SELECT query and display the results:

$sql = "SELECT id, name FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
  }
} else {
  echo "0 results";
}

Example 2: INSERT Query

Here's how to insert a new record into the database:

$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')";

if ($conn->query($sql) === TRUE) {
  echo "New record created successfully";
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}

4. Summary

In this tutorial, we've learned how to connect to a MySQL database using PHP, and how to execute SQL queries. We've also seen how to handle errors that may occur during the execution of queries.

The next step in your learning journey could be learning about prepared statements, which can make your queries safer.

5. Practice Exercises

  1. Write a PHP script that retrieves all users from the database, and displays their email addresses.
  2. Write a PHP script that updates the email address of a specific user.
  3. Write a PHP script that deletes a specific user from the database.

Remember, the best way to learn is by doing, so try to solve these exercises without looking at the solutions.

Solutions

Here's a possible solution for exercise 1:

$sql = "SELECT email FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) {
    echo "Email: " . $row["email"]. "<br>";
  }
} else {
  echo "0 results";
}

For exercises 2 and 3, you can simply modify the INSERT query example, replacing the INSERT keyword with UPDATE or DELETE, respectively.