What are some common pitfalls when trying to access and display data from a MySQL database using PHP?

One common pitfall when accessing and displaying 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. Another pitfall is not handling errors properly, which can lead to security vulnerabilities or unexpected behavior. Always check for errors and handle them appropriately in your code.

// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Prepare and execute a parameterized query
$stmt = $conn->prepare("SELECT * FROM table WHERE id = ?");
$stmt->bind_param("i", $id);

$id = 1;
$stmt->execute();

$result = $stmt->get_result();

// Display data
while ($row = $result->fetch_assoc()) {
    echo "Name: " . $row["name"] . "<br>";
    echo "Email: " . $row["email"] . "<br>";
}

// Close connection
$stmt->close();
$conn->close();