How can one ensure the security and integrity of data when using PHP for database operations?

To ensure the security and integrity of data when using PHP for database operations, it is important to use prepared statements with parameterized queries to prevent SQL injection attacks. Additionally, data validation and sanitization should be implemented to prevent any malicious input from being processed by the database.

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

// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (:username, :password)");

// Bind parameters to the placeholders
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);

// Sanitize and validate user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);

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