How can I prevent SQL injection in PHP?

Discussion RoomCategory: PHPHow can I prevent SQL injection in PHP?
Ashly asked 7 months ago

To prevent SQL injection in PHP:

  1. Use Prepared Statements: Use parameterized queries or prepared statements with PDO (PHP Data Objects) or MySQLi to bind user inputs securely.

Example (PDO):

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();

  1. Input Validation: Validate and sanitize user inputs to ensure they match the expected format or values.
  2. Escaping: If you can’t use prepared statements, escape user inputs with mysqli_real_escape_string() for MySQL or pg_escape_string() for PostgreSQL.

Example (MySQLi):

$username = mysqli_real_escape_string($conn, $username);

  1. Avoid Dynamic Queries: Avoid constructing SQL queries using string concatenation with user inputs.
  2. Limit Database Permissions: Grant minimal database privileges to the application, limiting its ability to modify the database structure.

By following these practices, you can significantly reduce the risk of SQL injection in PHP.

Scroll to Top