How can JOIN and ORDER BY clauses be used in SQL queries to filter and sort data effectively in PHP applications?
To filter and sort data effectively in PHP applications using SQL queries, you can use the JOIN clause to combine data from multiple tables based on a related column, and the ORDER BY clause to sort the results based on a specified column in ascending or descending order. Example PHP code snippet:
<?php
// Establish a connection to the database
$connection = new mysqli('localhost', 'username', 'password', 'database');
// SQL query to select data from two tables using JOIN and order by a specific column
$sql = "SELECT t1.column1, t2.column2
FROM table1 t1
JOIN table2 t2 ON t1.id = t2.id
ORDER BY t1.column1 DESC";
// Execute the query
$result = $connection->query($sql);
// Fetch and display the results
while($row = $result->fetch_assoc()) {
echo $row['column1'] . ' - ' . $row['column2'] . '<br>';
}
// Close the connection
$connection->close();
?>