What potential pitfalls should be considered when fetching and sorting data from different tables in PHP?

One potential pitfall when fetching and sorting data from different tables in PHP is the risk of SQL injection attacks if user input is not properly sanitized. To prevent this, always use prepared statements and parameterized queries when interacting with the database. Additionally, be cautious of potential data inconsistencies or errors that may arise when joining tables with different structures.

// Example of using prepared statements to fetch and sort data from different tables in PHP

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a SQL query to fetch data from two different tables and sort by a specific column
$stmt = $pdo->prepare("SELECT t1.column1, t2.column2 FROM table1 t1 JOIN table2 t2 ON t1.id = t2.table1_id ORDER BY t1.column1 ASC");

// Execute the query
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Loop through the results and output them
foreach($results as $row) {
    echo $row['column1'] . ' - ' . $row['column2'] . '<br>';
}