How can PHP beginners ensure their code is secure and protected from SQL injection attacks?

SQL injection attacks occur when malicious SQL statements are inserted into input fields, allowing attackers to manipulate the database. To prevent this, PHP beginners should use prepared statements with parameterized queries to sanitize user input and prevent SQL injection attacks.

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

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

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

// Set the username input from user input
$username = $_POST['username'];

// Execute the prepared statement
$stmt->execute();

// Process the result set
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Output data
    echo "Username: " . $row['username'];
}

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