Alex Rivera | Logout

What do the questions marks in SQL prepared statements mean?

Asked 2011-01-08T06:39:28.710
9

I found this in some code examples while googling :

$sql = 'INSERT INTO users (username,passwordHash) VALUES (?,?)';

it's new to me, but I would guess that it a substitution method and equivalent to

$sql = "INSERT INTO users (username,passwordHash) VALUES ($username,$passwordHash)";` 

or

$sql = 'INSERT INTO users (username,passwordHash) VALUES (' . $username . ',' . $passwordHash . ')';`

would that be correct? Is it an actual PHP syntax, or was he just trying to simplify his example?


Thanks for the feedback, folks

Edit
Report

1 Answer

5

The question marks are placeholders for values in prepared SQL statements - and are an important protection against SQL Injection Attacks. Your first alternative would not work properly unless every user encloses their name in quotes* and you enclose the password hash in quotes. Your second alternative is vulnerable to SQL Injection Attacks.

With placeholders, you pass the values for the placeholders when you execute the SQL.

* And Tim O'Reilly knows he really has to type "'Tim O''Reilly'".

answered 2011-01-08T06:46:33.403

Your Answer