Hacker News new | ask | show | jobs
by gbba 1676 days ago
Be careful as this syntax can potentially introduce SQL injections.

PHP's parameterization features in PDO can be abstracted so you can turn this into:

  $vars = array(":userid" => $userid);
  q("select name from users where id = :userid", $vars);
It's still pretty concise and is much safer.
2 comments

Two further alternatives for improved expressiveness:

  q('select name from users where id = :userid', compact('userid'));

  q('select name from users where id = ?', [ $userid ]);
Recommend using single quotes for SQL (command) literals, rather than doublequotes. This helps with discouraging string interpolation (" ... WHERE col = $value "). This also helps very much with SQL quoting object names (tables, columns, indexes, etc) - SQL specifies doublequote (") as the quoting character; for example 'SELECT COUNT(users.id) AS "Number of users" FROM users', or 'CREATE VIEW "My daily report" AS SELECT SUM("count") FROM "some strange table" LEFT JOIN ...'.
Parameterized queries and statements are great. They solve problems where the paramaterized queries are used. However care must be taken, a script running on the database after information has been entered can still inject long after the initial parameterized statement put it into the database if that script itself does not use parameterized queries, making a SQL injection still work, in a delayed way.