The Wayback Machine - https://web.archive.org/web/20240625183346/https://www.geeksforgeeks.org/php-mysql-select-query/
Open In App

PHP | MySQL Select Query

Last Updated : 26 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report
The SQL SELECT statement is used to select the records from database tables.
Syntax : The basic syntax of the select clause is –
To select all columns from the table, the  * character is used.
Implementation of the Select Query : Let us consider the following table ‘ Data ‘ with three columns ‘ FirstName ‘, ‘ LastName ‘ and ‘ Age ‘.
To select all the data stored in the ‘ Data ‘ table, we will use the code mentioned below. SELECT Query using Procedural Method :
<?php 
$link = mysqli_connect("localhost", "root", "", "Mydb");
  
if ($link === false) {
    die("ERROR: Could not connect. "
                .mysqli_connect_error());
}
  
$sql = "SELECT * FROM Data";
if ($res = mysqli_query($link, $sql)) {
    if (mysqli_num_rows($res) > 0) {
        echo "<table>";
        echo "<tr>";
        echo "<th>Firstname</th>";
        echo "<th>Lastname</th>";
        echo "<th>age</th>";
        echo "</tr>";
        while ($row = mysqli_fetch_array($res)) {
            echo "<tr>";
            echo "<td>".$row['Firstname']."</td>";
            echo "<td>".$row['Lastname']."</td>";
            echo "<td>".$row['Age']."</td>";
            echo "</tr>";
        }
        echo "</table>";
        mysqli_free_result($res);
    }
    else {
        echo "No matching records are found.";
    }
}
else {
    echo "ERROR: Could not able to execute $sql. "
                                .mysqli_error($link);
}
mysqli_close($link);
?>

                    
Output :
Code Explanation:
  1. The “res” variable stores the data that is returned by the function mysql_query().
  2. Everytime mysqli_fetch_array() is invoked, it returns the next row from the res() set.
  3. The while loop is used to loop through all the rows of the table “data”.

SELECT Query using Object Oriented Method :
<?php
$mysqli = new mysqli("localhost", "root", "", "Mydb");
  
if ($mysqli === false) {
    die("ERROR: Could not connect. "
                          .$mysqli->connect_error);
}
  
$sql = "SELECT * FROM Data";
if ($res = $mysqli->query($sql)) {
    if ($res->num_rows > 0) {
        echo "<table>";
        echo "<tr>";
        echo "<th>Firstname</th>";
        echo "<th>Lastname</th>";
        echo "<th>Age</th>";
        echo "</tr>";
        while ($row = $res->fetch_array()) 
        {
            echo "<tr>";
            echo "<td>".$row['Firstname']."</td>";
            echo "<td>".$row['Lastname']."</td>";
            echo "<td>".$row['Age']."</td>";
            echo "</tr>";
        }
        echo "</table>";
        $res->free();
    }
    else {
        echo "No matching records are found.";
    }
}
else {
    echo "ERROR: Could not able to execute $sql. "
                                             .$mysqli->error;
}
$mysqli->close();
?>

                    
Output :
SELECT Query using PDO Method :
<?php 
try {
    $pdo = new PDO("mysql:host = localhost;
                      dbname=mydb", "root", "");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, 
                        PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
    die("ERROR: Could not connect. ".$e->getMessage());
}
try {
    $sql = "SELECT * FROM Data";
    $res = $pdo->query($sql);
    if ($res->rowCount() > 0) {
        echo "<table>";
        echo "<tr>";
        echo "<th>Firstname</th>";
        echo "<th>Lastname</th>";
        echo "<th>Age</th>";
        echo "</tr>";
        while ($row = $res->fetch()) {
            echo "<tr>";
            echo "<td>".$row['Firstname']."</td>";
            echo "<td>".$row['Lastname']."</td>";
            echo "<td>".$row['Age']."</td>";
            echo "</tr>";
        }
        echo "</table>";
        unset($res);
    }
    else {
        echo "No matching records are found.";
    }
}
catch (PDOException $e) {
    die("ERROR: Could not able to execute $sql. "
                                .$e->getMessage());
}
unset($pdo);
?>

                    
Output :


Previous Article
Next Article

Similar Reads

PHP | MySQL UPDATE Query
The MySQL UPDATE query is used to update existing records in a table in a MySQL database. It can be used to update one or more field at the same time. It can be used to specify any condition using the WHERE clause. Syntax : The basic syntax of the Update Query is - Implementation of Where Update Query : Let us consider the following table "Data" wi
2 min read
PHP | MySQL Delete Query
The DELETE query is used to delete records from a database table. It is generally used along with the "Select" statement to delete only those records that satisfy a specific condition. Syntax : The basic syntax of the Delete Query is - Let us consider the following table "Data" with four columns ' ID ', ' FirstName ', ' LastName ' and ' Age '. To d
2 min read
PHP - MySQL : Nested Query
In this article, we are going to perform nested query operations on the database in the MySQL server using the Xampp server. Introduction : PHP stands for hypertext preprocessor, which is a server-side scripting language and also used to handle database operations. We are a PHP xampp server to communicate with the database. The language used is MyS
5 min read
How to remove all the options of a select box and then add one option and select it using JQuery ?
Given a select box with a fixed number of options, the task is to remove all the options and then add one option and immediately select that particular option using jQuery. There are two approaches that can be taken to achieve this: Approach 1: Using find(), remove(), end() and append() Methods: In the following example, a select box with some opti
3 min read
Select different values on two select tags in Vue.js
In this article, we will see the selection of different values on a single select and two &lt;select&gt; tags in vue.js, along with understanding their basic implementation through the examples. HTML &lt;select&gt; tag is used to create a drop-down list. Adding a list of options inside the drop-down list using the &lt;option&gt; tag. when we select
6 min read
SQL | Query to select NAME from table using different options
Let us consider the following table named "Geeks" : G_ID FIRSTNAME LASTNAME DEPARTMENT 1 Mohan Arora DBA 2 Nisha Verma Admin 3 Vishal Gupta DBA 4 Amita Singh Writer 5 Vishal Diwan Admin 6 Vinod Diwan Review 7 Sheetal Kumar Review 8 Geeta Chauhan Admin 9 Mona Mishra Writer SQL query to write “FIRSTNAME” from Geeks table using the alias name as NAME.
2 min read
Python MariaDB - Select Query using PyMySQL
MariaDB is an open source Database Management System and its predecessor to MySQL. The pymysql client can be used to interact with MariaDB similar to that of MySQL using Python. In this article we will look into the process of querying data from a table of the database using pymysql. To query data use the following syntax: Syntax : In order to sele
2 min read
SQL Query to select Data from Tables Using Join and Where
The aim of this article is to make a simple program to Join two tables using Join and Where clause using MySQL. Below is the method to do the same using MySQL. The prerequisites of this article are MySQL and Apache Server on your computer are installed. What is a Query in SQL? A SQL query is a request passed for data/information from a table in a d
3 min read
SQL Query to Select all Records From Employee Table Where Name is Not Specified
Here, we are going to see how to find the names of the persons other than a person with a particular name SQL. In this article, we will be making use of the MSSQL Server as our database. For example, if the employee name is Pradeep you need to show the table of employees excluding that employee with the name Pradeep. So let us execute this query in
2 min read
Mongoose Query prototype.select() API
Mongoose is an Object Data Modeling (ODM) library for MongoDB. It defines a strongly-typed schema, with default values and schema validations which are later mapped to a MongoDB document. Mongoose Query API select method is used to determine which document fields to select or deselect while fetching them from the DB. Let's understand more about thi
3 min read
Article Tags :
three90RightbarBannerImg