How can PHP developers optimize their code to prevent SQL injection vulnerabilities when inserting data into a MySQL database?

SQL injection vulnerabilities can be prevented by using prepared statements with parameterized queries in PHP when inserting data into a MySQL database. This approach ensures that user input is treated as data, not as part of the SQL query, thereby preventing malicious SQL injection attacks.

// Establish a connection to the MySQL database
$connection = new mysqli($servername, $username, $password, $dbname);

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

// Bind parameters to the prepared statement
$stmt->bind_param("ss", $value1, $value2);

// Set parameter values
$value1 = $_POST['value1'];
$value2 = $_POST['value2'];

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

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