Skip to content
PHP Logo

What is the potential issue with the PHP code provided for inserting data into a database?

The potential issue with the provided PHP code is that it is vulnerable to SQL injection attacks as it directly inserts user input into the SQL query without sanitization. To solve this issue, you should use prepared statements with parameterized queries to prevent SQL injection attacks.

php
// Fix for inserting data into a database using prepared statements

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare the SQL statement with placeholders
$stmt = $pdo->prepare("INSERT INTO mytable (column1, column2) VALUES (:value1, :value2)");

// Bind the parameters with the actual values
$stmt->bindParam(':value1', $value1);
$stmt->bindParam(':value2', $value2);

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

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