What are potential pitfalls to watch out for when inserting data into a database using PHP, and how can they be avoided?
One potential pitfall when inserting data into a database using PHP is SQL injection attacks. To avoid this, always use prepared statements with parameterized queries to sanitize user input.
// Connect to the database
$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', $username);
$stmt->bindParam(':email', $email);
// Set the parameters and execute the query
$username = $_POST['username'];
$email = $_POST['email'];
$stmt->execute();