PHP / PHP Database Integration

Executing SQL Queries in PHP

This tutorial will guide you through the process of executing SQL queries in PHP, enabling you to interact with your database.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Introduces connecting PHP with databases using MySQL and PDO.

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.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

CSV to JSON Converter

Convert CSV files to JSON format and vice versa.

Use tool

Image Converter

Convert between different image formats.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

Backlink Checker

Analyze and validate backlinks.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help