How can variables be validated before executing an SQL query in PHP?

To validate variables before executing an SQL query in PHP, you can use prepared statements with parameterized queries. This helps prevent SQL injection attacks by separating SQL code from user input. By binding variables to placeholders in the query, you ensure that the input is treated as data rather than executable code.

// 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 users WHERE username = :username');

// Bind the variable to the parameter in the query
$username = $_POST['username'];
$stmt->bindParam(':username', $username, PDO::PARAM_STR);

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

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