What are some potential pitfalls to avoid when working with database connection and data writing in PHP?

One potential pitfall to avoid when working with database connection and data writing in PHP is not properly sanitizing user input before inserting it into the database. This can lead to SQL injection attacks and compromise the security of your application. To prevent this, always use prepared statements with parameterized queries to securely interact with 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, email) VALUES (:username, :email)");

// Bind parameters to the placeholders
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':email', $_POST['email']);

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