How can SQL injection vulnerabilities be prevented when inserting data into a SQL database using PHP?
SQL injection vulnerabilities can be prevented by using prepared statements with parameterized queries in PHP when inserting data into a SQL database. This method separates the SQL query from the user input, preventing malicious SQL code from being executed.
// Establish a connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');
// Prepare a SQL query using a parameterized query
$stmt = $pdo->prepare("INSERT INTO my_table (column1, column2) VALUES (:value1, :value2)");
// Bind the parameters with the user input
$stmt->bindParam(':value1', $userInput1);
$stmt->bindParam(':value2', $userInput2);
// Execute the query
$stmt->execute();