PHP MySQL Select Data
Select Data From a MySQL Database
To select data from mysql, you must have some basic knowledge of SQL SELECT query.
The SELECT
command is used to select data from Mysql tables.
The following syntax is used to select data from a table with one or more specified columns:
SELECT column_name(s) FROM table_name
You can select ALL columns from the table with the *
character:
SELECT * FROM table_name
You can use more options with SELECT
command to filter data using WHERE
command, getting ascending or descending ordered result using ORDER BY
command, limiting
the query result using LIMIT
command and more.
Select Data From MySql With MySQLi and PDO
PHP provides many useful methods and properties to work with database result. We are going to use num_rows
property and fetch_assoc()
method in this below program.
We will take a sample table called "Employee" and it contains three columns ("id", "name", and "city") and three records.
ID | Name | City |
---|---|---|
1 | Suresh | Paris |
2 | Babu | London |
3 | Kumar | New York |
Example (MySQLi Object-oriented)
The num_rows
property is used to return number of records available in the query result.
The fetch_assoc()
method return query results (All rows and cols) as a associative array.
connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Employee";
$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"]. " , City = " . $row["city"] . "
";
}
} else {
echo "0 results";
}
$conn->close();
?>
Output :-
ID = 2 , Name = Babu , City = London
ID = 3 , Name = Kumar , City = New York
Code Explained:
First, we establish a SQL query, which select all columns and rows from the Employee table.
The next line of code will conduct the query and place the returned information into a $result
variable.
The $result
variable contains the query result.
The num_rows
property then checks for the return of more than zero rows.
If more than 0 rows are returned, the fetch_assoc()
function can be used to place all the results (rows and cols) into an associated array.
The while()
loops the results of the ID, name and city columns and prints the data of each row one by one.
Example (MySQLi Procedural)
The mysqli_num_rows()
function is used to return number of records available in the query result.
The mysqli_fetch_assoc()
method return query results (All rows and cols) as a associative array.
The following example displays the same thing as the previous one, but in a MySQLi procedural manner :
connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Employee";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "
ID = " . $row["id"]. " , Name = ". $row["name"]. " , City = " . $row["city"] . "
";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Example (PDO)
The fetchAll()
method return query results (All rows and cols) as a associative array.
The following example displays the same thing as the previous one, but in a MySQLi procedural manner :
query('SELECT * FROM Employee');
// fetch all rows into array
$rows = $stm->fetchAll();
// iterate over array by index and by name
foreach($rows as $row) {
echo "
ID = " . $row["id"]. " , Name = ". $row["name"]. " , City = " . $row["city"] . "
";
}
} catch(PDOException $e) {
echo $sql . "
" . $e->getMessage();
}
// Close connection
$conn = null;
?>
Related Links
Display MySql Query Results in HTML Table Format
You may also use HTML tables to display the query results in a tabular format:
Example (MySQLi Object-oriented) :- The following program will display the query result in a table format using html tables:
connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Employee";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo " ID Name City ";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "" . $row["id"]. " ". $row["name"]. " " . $row["city"] . " ";
}
echo "
";
} else {
echo "0 results";
}
$conn->close();
?>
Output:-
ID | Name | City |
---|---|---|
1 | Suresh | Paris |
2 | Babu | London |
3 | Kumar | New York |
Select and Filter Data From a MySQL Database
To filter records, the WHERE
clause is utilized.
The WHERE
clause only allows records that meet a specific requirement to be extracted.
SELECT column_name(s) FROM table_name WHERE column_name operator value
Select and Filter Data With MySQLi
This example picks the id, name, and city from the "Employee" table where the city is "London", and shows it on the page: The following example is :
connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Employee WHERE city = 'London'";
$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"]. " , City = " . $row["city"] . "
";
}
} else {
echo "0 results";
}
$conn->close();
?>
Output :-
Select and Order Data From a MySQL Database
In order to arrange the results in ascending or descending order, the ORDER BY
clause is needed.
By default, the ORDER BY
clause orders the records in ascending. The DESC
keyword is used to sort the records in ascending order.
SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC
Select and Order Data With MySQLi
In the example below, The city field will be used to sort the data, table in "Employee" are selected and shown on the page :
connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Employee ORDER BY city";
$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"]. " , City = " . $row["city"] . "
";
}
} else {
echo "0 results";
}
$conn->close();
?>
Output :-
ID = 3 , Name = Kumar , City = New York
ID = 1 , Name = Suresh , City = Paris
Related Links
Limit Data Selections From a MySQL Database
The LIMIT
clause in MySQL is used to limit how many records are returned.
LIMIT Data highly useful on huge tables to easily implement multi-page results or pagination with SQL. A huge quantity of recordings can have an effect on performance.
Suppose we would like to pick from the "Employee" table all records from 1 - 20 (included)." The SQL query looks like that :
$sql = "SELECT * FROM Employee LIMIT 20";
Once the above SQL query is executed, the first 20 records will be returned.
If you want to pick records within a range, Mysql also has a solution for this : use the OFFSET
clause.
"Return only 10 records and start record 16" the following SQL query reads (OFFSET 15) :
$sql = "SELECT * FROM Employee LIMIT 10 OFFSET 15";
In order to get the same outcome you can also use a short syntax :
$sql = "SELECT * FROM Employee LIMIT 15, 10";
When you use a comma, you will notice that the numbers are reversed.