Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Will Feldman
Will Feldman
3,121 Points

SQL Injection with PHP

Is this safe from SQL injection?

$sql = "SELECT * FROM database WHERE email='$_POST[email]' AND password='$_POST[password]'";
$result = mysqli_query($conn, $sql);

if (mysqli_query($conn, $sql)) {
    $connected = 1;
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);

1 Answer

Hi Will,

Unfortunately not. A better method would be to avoid putting $_POST directly into SQL statements altogether and instead assigning them to a variable after sanitizing them. Take a look and the variants of filter_sanitize.


If you absolutely have to put POST data into the SQL, wrap them in mysqli_real_escape_string within the statement.



$_POST data can easily be modified allowing a statement such as: SELECT * FROM database WHERE email='example@example.com' AND password='password123' to become SELECT * FROM database WHERE email='example@example.com' AND password='password123'; DROP TABLE table_name;" simply by modifying $_POST['password'] data. The user could simply set their password to be password123'; DROP TABLE table_name; (Providing that there was no sanitization on the password field)