What are some best practices for structuring PHP code to avoid vulnerabilities like SQL injection?

SQL injection vulnerabilities can be avoided by using prepared statements with parameterized queries in PHP. This helps to separate SQL code from user input, preventing malicious SQL queries from being executed. Example PHP code snippet using prepared statements to prevent SQL injection:

// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

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

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

// Prepare a SQL statement with a parameter
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Set the parameter value and execute the statement
$username = $_POST['username'];
$stmt->execute();

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

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