How can SQL injection vulnerabilities be avoided when inserting form data into a database using PHP?

SQL injection vulnerabilities can be avoided by using prepared statements and parameterized queries when inserting form data into a database using PHP. This helps to prevent malicious SQL code from being injected into the query, as the input data is treated as data rather than executable code.

// Establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Prepare a SQL statement with a parameterized query
$stmt = $mysqli->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");

// Bind the form data to the parameters in the query
$stmt->bind_param("ss", $form_data1, $form_data2);

// Assign form data to variables
$form_data1 = $_POST['form_field1'];
$form_data2 = $_POST['form_field2'];

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

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