by npteljes · 5y ago · 0 comments
In a similar fashion, I abstracted away the database connection, query and returning of results into one lazy-inited function, so talking to the database really was just like
<?=q("select name from users where id = $userid") ?>
I worked a lot with other languages, none feeling as natural to me as this one, aside from Ruby.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. 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 ...'.