How can PDO and prepared statements improve data security and prevent duplicate entries in PHP?
Using PDO and prepared statements in PHP can improve data security by preventing SQL injection attacks. Prepared statements separate SQL code from user input, making it impossible for malicious input to alter the SQL query structure. Additionally, using prepared statements can help prevent duplicate entries by allowing you to check if a record already exists before inserting new data.
// Establish a connection to the database using PDO
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL statement with a placeholder for user input
$stmt = $pdo->prepare("SELECT * FROM mytable WHERE column = :input");
// Bind the user input to the placeholder
$stmt->bindParam(':input', $user_input);
// Execute the statement
$stmt->execute();
// Check if a record already exists
if($stmt->rowCount() > 0) {
echo "Record already exists.";
} else {
// Insert new data if no duplicate entry found
$stmt = $pdo->prepare("INSERT INTO mytable (column) VALUES (:input)");
$stmt->bindParam(':input', $user_input);
$stmt->execute();
}