What are the best practices to prevent SQL injection when saving user inputs in a database using PHP?
SQL injection can be prevented by using prepared statements with parameterized queries in PHP. This technique ensures that user input is treated as data rather than executable code, thus preventing malicious SQL injection attacks.
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');
// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (:username, :password)");
// Bind parameters to the placeholders
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':password', $_POST['password']);
// Execute the prepared statement
$stmt->execute();
Keywords
Related Questions
- How can PHP scripts retrieve and display unique identifiers (IDs) for uploaded files while avoiding displaying all other IDs simultaneously?
- How can assigning objects to variables affect the functionality of PHP code when returning arrays from functions?
- How can proper debugging techniques help in resolving PHP code errors more efficiently?