VOOZH about

URL: https://www.geeksforgeeks.org/php/how-to-execute-an-sql-query-and-fetch-results-using-php/

⇱ How to execute an SQL query and fetch results using PHP ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to execute an SQL query and fetch results using PHP ?

Last Updated : 23 Jul, 2025

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.

Output:

Database has been created successfully

Creating the table:

Output:

Table has been created successfully

Inserting some values into the table "Emp":

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:

Output:

id: 1 - Name: XYZ ABC
Comment
Article Tags: