How can PHP beginners avoid pitfalls when handling text data in MySQL queries?

When handling text data in MySQL queries, PHP beginners should always use prepared statements to prevent SQL injection attacks and ensure proper escaping of special characters. This can be achieved by using parameterized queries with placeholders for dynamic data.

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

// Prepare a SQL statement with a placeholder
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind the parameter value to the placeholder
$stmt->bindParam(':username', $username);

// Execute the query
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();