Skip to content
PHP Logo

What are the potential pitfalls of using DESC and ASC in ORDER BY statements in PHP?

Using DESC and ASC in ORDER BY statements can lead to SQL injection vulnerabilities if the input is not properly sanitized. To avoid this issue, it's recommended to use prepared statements with parameterized queries in PHP to prevent malicious SQL injection attacks.

php
// Example of using prepared statements in PHP to prevent SQL injection

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

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare('SELECT * FROM mytable ORDER BY column_name DESC');

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

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

// Loop through the results
foreach ($results as $row) {
    // Output the data
    echo $row['column_name'] . '<br>';
}