What are some best practices for input validation in PHP to prevent database issues like SQL injection or data format errors?

SQL injection can be prevented by using prepared statements and parameterized queries in PHP. This helps to separate SQL code from user input, making it impossible for malicious input to alter the SQL query structure. Data format errors can be avoided by validating input data against expected formats using PHP functions like filter_var() or regular expressions.

// Prevent SQL injection
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();

// Validate input data format
$email = $_POST['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email format";
}