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
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;
}
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";
}
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;
}
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.
Remember, the best way to learn is by doing, so try to solve these exercises without looking at the 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.