Example of Vulnerable Code (Unsafe)
Code: Select all
$userid = $_GET['id'];
$query = "SELECT * FROM users WHERE id = '$userid'";
$result = mysqli_query($conn, $query);
Safe Code Using Prepared Statements (PHP & MySQLi)
Code: Select all
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $userid);
$stmt->execute();
$result = $stmt->get_result();
Other security measures include:
Input Validation: Restrict input types to only expected values.
Escaping User Inputs: Use functions like mysqli_real_escape_string().
Least Privilege Principle: Limit database user permissions.
Use Web Application Firewalls: Prevent automated attacks.
By following these best practices, you can protect your application from SQL injection and other security threats