How to prevent sql injection in php?

SQL injection is a code injection technique that exploits a security vulnerability in an application's software.

Example:


  $username = $_POST['username'];
  $password = $_POST['password'];
  $sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
  

This approach is vulnerable to SQL injection.

Solution:


  $stmt = $conn->prepare('SELECT * FROM users WHERE username = ? AND password = ?');
  $stmt->bind_param('ss', $username, $password);
  

Beginner's Guide to PHP