What are common pitfalls when using MySQL in PHP for database connections and queries?

Common pitfalls when using MySQL in PHP include not sanitizing user input before using it in queries, not using prepared statements to prevent SQL injection attacks, and not properly handling errors that may occur during database operations. To solve these issues, always sanitize user input using functions like mysqli_real_escape_string(), use prepared statements with placeholders for dynamic data, and implement error handling to catch and handle any database errors.

// 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);
}

// Sanitize user input
$user_input = mysqli_real_escape_string($conn, $_POST['user_input']);

// Prepare and execute a prepared statement
$stmt = $conn->prepare("SELECT * FROM table WHERE column = ?");
$stmt->bind_param("s", $user_input);
$stmt->execute();

// Handle errors
if ($stmt->error) {
    die("Error: " . $stmt->error);
}

// Process results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Process each row
}

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