What are the potential security risks associated with dynamically sorting a MySQL table using PHP?

When dynamically sorting a MySQL table using PHP, the potential security risk is SQL injection. This can occur if user input is not properly sanitized before being used in the SQL query. To prevent SQL injection, use prepared statements with parameterized queries to securely handle user input.

// Assume $sort_column and $sort_order are user input values
$sort_column = $_GET['sort_column'];
$sort_order = $_GET['sort_order'];

// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare the SQL query with parameters
$stmt = $pdo->prepare("SELECT * FROM mytable ORDER BY $sort_column $sort_order");

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

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

// Output the results
foreach ($results as $row) {
    echo $row['column1'] . ' - ' . $row['column2'] . '<br>';
}