Home » Php » php – What does this mean?

php – What does this mean?

Posted by: admin July 12, 2020 Leave a comment

Questions:

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

How to&Answers:

This is pretty common in prepared statements. The ? merely serves as a placeholder, as seen below from the PHP documentation:

$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();

Answer:

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'“.

Answer:

it’s not the same. question marks are used for prepared statement queries. these basically allow you to run the same query multiple times while only having the system parse the query once.