What are common pitfalls when using PHP for SQL queries, as seen in the provided forum thread?

Common pitfalls when using PHP for SQL queries include not properly sanitizing user input, not using prepared statements to prevent SQL injection attacks, and not handling errors effectively. 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 SQL errors that may occur.

// Example of using prepared statements with mysqli to prevent SQL injection
$mysqli = new mysqli("localhost", "username", "password", "database");

if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

$username = $_POST['username'];
$stmt->execute();

$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    // Process the fetched data
}

$stmt->close();
$mysqli->close();