How can PHP developers ensure data security and prevent SQL injection when inserting data into a database table using PHP?
To ensure data security and prevent SQL injection when inserting data into a database table using PHP, developers should use prepared statements with parameterized queries. This helps to separate the SQL query logic from the user input data, making it impossible for malicious SQL code to be injected into the query.
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL query with placeholders for user input
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");
// Bind the user input data to the placeholders
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
// Execute the query
$stmt->execute();