How can one ensure proper validation and filtering of user input in PHP when interacting with a database?
To ensure proper validation and filtering of user input in PHP when interacting with a database, it is essential to use prepared statements with parameterized queries to prevent SQL injection attacks. Additionally, input validation functions such as filter_var() can be used to sanitize and validate user input before inserting it into the database.
// Example of using prepared statements with parameterized queries to interact with a MySQL database
// 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('INSERT INTO users (username, email) VALUES (:username, :email)');
// Sanitize and validate user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
// Bind parameters and execute the statement
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
$stmt->execute();