What are some common functions or methods in PHP that can help prevent SQL injection when dealing with string variables in MySQL queries?

SQL injection is a common attack where malicious SQL statements are inserted into an entry field for execution. To prevent SQL injection when dealing with string variables in MySQL queries in PHP, you can use prepared statements with parameterized queries. This method separates SQL code from user input, making it impossible for an attacker to inject malicious code.

// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

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

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

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