What are common pitfalls when using multiple SQL queries in PHP, and how can they be avoided?

Common pitfalls when using multiple SQL queries in PHP include not properly sanitizing user input, not handling errors effectively, and not closing database connections after use. To avoid these pitfalls, always use prepared statements to prevent SQL injection attacks, check for errors after executing each query, and close the database connection when it is no longer needed.

// Example of using prepared statements to avoid SQL injection

// Establish a database connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Prepare a SQL statement
$stmt = $conn->prepare("INSERT INTO users (username, email) VALUES (?, ?)");

// Bind parameters
$stmt->bind_param("ss", $username, $email);

// Set parameters and execute query
$username = "john_doe";
$email = "john.doe@example.com";
$stmt->execute();

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