Current Location: Home> Latest Articles> PHP Database Query, Filtering, and Sorting: Practical Techniques and Methods

PHP Database Query, Filtering, and Sorting: Practical Techniques and Methods

gitbox 2025-06-30

Introduction

When developing PHP applications, database queries and result filtering functions are common operations. Through database queries, developers can retrieve the required data and further optimize its presentation by using filtering and sorting methods. This article discusses how to use database queries and filtering functions in PHP for data selection and sorting.

Database Queries

Connecting to the Database

Before performing any queries, the first step is to establish a connection to the database. This can be done using the mysqli_connect function in PHP:


$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

This code attempts to connect to the database named myDB. If the connection fails, an error message will be displayed.

Executing a Query

Once the connection is established, you can execute a SQL query using the mysqli_query function:


$sql = "SELECT * FROM users WHERE age > 18";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    // Process the query result
} else {
    echo "No data found matching the criteria.";
}

This code queries the users table and selects users whose age is greater than 18.

Data Filtering and Sorting

Data Filtering

After retrieving query results, you can use PHP functions to filter the results further. For example, to filter users whose email contains 'example.com', you can use the strpos function:


while ($row = mysqli_fetch_assoc($result)) {
    if (strpos($row['email'], 'example.com') !== false) {
        // Process the filtered data
}
}

This code will only process users whose email contains 'example.com'.

Data Sorting

It is often necessary to sort query results based on a specific field. You can achieve this by using the ORDER BY clause in your SQL query. For example, to sort users by age in ascending order:


$sql = "SELECT * FROM users WHERE age > 18 ORDER BY age ASC";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
    // Process the sorted data
}

This code will return users older than 18 and sort them by age in ascending order.

Closing the Connection

After completing the queries, you should close the database connection to free up resources:


mysqli_close($conn);

This code will close the connection to the database.

Conclusion

This article provided a detailed guide on how to use database queries, filtering, and sorting functions in PHP. By following these steps, developers can flexibly handle and display data from databases. Mastering these techniques will help you improve the efficiency and flexibility of PHP database operations.