What potential pitfalls should be avoided when connecting PHP with SQL databases?

One potential pitfall to avoid when connecting PHP with SQL databases is SQL injection attacks. To prevent this, always use prepared statements with parameterized queries to sanitize user input and avoid directly inserting user input into SQL queries.

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

// Use prepared statements to prevent SQL injection
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

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

// Fetch results
$result = $stmt->get_result();

// Process results
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

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