How can you prevent SQL errors when building dynamic SQL statements in PHP based on user input?

To prevent SQL errors when building dynamic SQL statements in PHP based on user input, you should use prepared statements with parameterized queries. This approach helps to sanitize user input and prevent SQL injection attacks by separating the SQL query logic from the user input data.

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

// User input
$userInput = $_POST['user_input'];

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the user input to the parameter
$stmt->bindParam(':username', $userInput, PDO::PARAM_STR);

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

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

// Process the results as needed
foreach($results as $row) {
    // Do something with the data
}