How to execute an SQL query and fetch results using PHP ?
Last Updated :
18 Apr, 2022
In this article, we will discuss how to execute an SQL query and how to fetch its result?
We can perform a query against the database using the PHP mysqli_query() method.
Syntax: We can use the mysqli_query( ) method in two ways:
- Object-oriented style
- Procedural style
Parameters:
- connection: It is required that specifies the connection to use.
- query: It is also required that specifies the database query.
- result mode: It is optional to use.
Return value: For SELECT, SHOW, DESCRIBE, or EXPLAIN it returns a mysqli_result object. For other successful queries, it returns true. Otherwise, it returns false on failure.
Let's understand how we can execute an SQL query.
Executing an SQL query: We will understand how we can execute an SQL query with an example. We will create a database, table and then insert some values into it.
Example: Create a database and insert some values into it.
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "CREATE DATABASE gfgDB";
if ($conn->query($sql) === TRUE) {
echo "Database has been created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
Output:
Database has been created successfully
Creating the table:
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gfgDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "CREATE TABLE Emp (
id INT(6) AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL
)";
if ($conn->query($sql) === TRUE) {
echo "Table has been created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
Output:
Table has been created successfully
Inserting some values into the table "Emp":
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gfgDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Emp (firstname, lastname)
VALUES ('XYZ', 'ABC')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
}else{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Output:
New record created successfully
Note: Since we have used AUTO_INCREMENT, it will automatically insert the record with "id=1" and for each newly inserted record, it will increase the "id" by one.
Fetching results from the database:
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gfgDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM Emp";
$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 "No records has been found";
}
$conn->close();
?>
Output:
id: 1 - Name: XYZ ABC
Similar Reads
How to Execute SQL queries from CGI scripts In this article, we will explore the process of executing SQL queries from CGI scripts. To achieve this, we have developed a CGI script that involves importing the database we created. The focus of this discussion will be on writing code to execute SQL queries in Python CGI scripts. The initial step
5 min read
SQL Query to Select Data from Tables Using Join and Where In SQL, the JOIN clause combines data from multiple tables based on a common column, while the WHERE clause filters the results based on specific conditions. Together, they allow us to retrieve relevant data efficiently from related tables. This article will guide us in using SQL JOIN and WHERE clau
5 min read
Create a Small CRM using PHP and MySQL CRM stands for Customer Relationship Management, which is a strategy for a set of practices, and a technology designed to manage and analyze customer interactions and data throughout the customer lifecycle. Manage contacts by adding, updating, and deleting information such as name, email, phone, and
6 min read
Insert data from one table to another table using PHP In this article, we are going to insert data into another table from the existing table using PHP. Requirements: XAMPP Webserver PHP stands for Hypertext preprocessor. MySQL is a database query language for performing database operations. We are going to insert data from one table into another table
2 min read
How to retrieve data from MySQL database using PHP ? There are steps to understand for retrieving the data from the MySQL database. Approach: Create the database, then create the table for data.Enter the rows in the table. You have to connect to the database. Now we understand each and every step as shown below.  Example 1: In this. we use PHPMyAdmin
2 min read