Skip to main content

Correct code

Using PDO (PHP Data Objects) is an excellent practice to prevent SQL injections in PHP, thanks to its focus on prepared statements. This method allows data to be separated from SQL statements, thus preventing attackers from injecting malicious code. Here is a detailed explanation and best practices to follow when using PDO in your PHP applications:

Database connection with PDO

To establish a secure connection to the database using PDO, exception handling is recommended to effectively detect connection errors.

<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// Establece el modo de error a excepción para capturar y manejar errores adecuadamente
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>

Perform secure queries using Prepared Statements

The prepared statements ensure that the data provided by users is not evaluated as SQL code, thus avoiding the execution of SQL injections.

Data Query

<?php
// Preparar la consulta
$stmt = $conn->prepare("SELECT * FROM users WHERE email = :email AND password = :password");

// Asignar valores a los parámetros
$email = 'user@example.com';
$password = 'user_password';
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password);

// Ejecutar la consulta
$stmt->execute();

// Obtener los resultados
$result = $stmt->fetch(PDO::FETCH_ASSOC);
?>

Insert data

<?php
// Preparar la consulta
$stmt = $conn->prepare("INSERT INTO users (username, email, password) VALUES (:username, :email, :password)");

// Asignar valores a los parámetros
$username = 'new_user';
$email = 'newuser@example.com';
$password = 'new_password';
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password);

// Ejecutar la consulta
$stmt->execute();
?>

Update data

<?php
// Preparar la consulta
$stmt = $conn->prepare("UPDATE users SET email = :email, password = :password WHERE id = :id");

// Asignar valores a los parámetros
$email = 'updateduser@example.com';
$password = 'updated_password';
$id = 1;
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password);
$stmt->bindParam(':id', $id);

// Ejecutar la consulta
$stmt->execute();
?>

Delete data

<?php
// Preparar la consulta
$stmt = $conn->prepare("DELETE FROM users WHERE id = :id");

// Asignar valores a los parámetros
$id = 2;
$stmt->bindParam(':id', $id);

// Ejecutar la consulta
$stmt->execute();
?>

Best Practices and Additional Considerations

  • Data Validation: In addition to using prepared queries, validate and sanitize input data to enhance security.
  • Using Secure Passwords To store passwords, use secure hashing functions such as password_hash() and password_verify() in PHP.
  • Configuration Security: Secure your PHP configuration and database to minimize additional risks.
  • Updates and Continuous Training: Keep up to date with the latest practices and vulnerabilities by following resources such as OWASP.

Implementing these practices not only improves the security of your applications but also contributes to a more robust and reliable development environment.