What are some common pitfalls to avoid when retrieving and storing data from a MySQL database using PHP?

One common pitfall to avoid when retrieving and storing data from a MySQL database using PHP is not properly sanitizing user input, which can lead to SQL injection attacks. To prevent this, always use prepared statements with parameterized queries to securely pass user input to the database.

// Example of using prepared statements to retrieve data from a MySQL database in PHP

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

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

// Bind the parameter value
$stmt->bindParam(':username', $_POST['username']);

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

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

// Loop through the results and do something with the data
foreach ($results as $row) {
    echo $row['username'] . '<br>';
}