I have been refactoring a lot of my old code lately, and with that I have been switching from sqlite3 to mysql using PDO - sqlite3 has something called "querysingle" that allows you to return single responses (as a row or a single value) from a database table.
Anyways, I really liked the simplicity of this and that it all fits in 1 line of code and (IMO) doesn't harm the readability of the code.
I wrote a function in PHP that does a similar thing, but I wanted to make sure that I wasn't missing any edge cases, or see if I could improve the function in any way.
Here is my function:
function pdoQuerySingle($con, $query, $values = array(), $single = false) {
if($values) {
$stmt = $con->prepare($query);
$stmt->execute($values);
} else {
$stmt = $con->query($query);
}
if($single) return $stmt->fetch()[$single];
return $stmt->fetch();
}
You use it as follows:
$variable = pdoQuerySingle($pdo, "SELECT * FROM table WHERE id=?", [$id]);
As you can see this query works with prepared statements for security against SQL injection, though you can leave the 3rd param empty if you aren't passing any values to the query. The 4th parameter can be used to return only a specific entry from the query return as a string so if you wanted $variable
to be set to a string from a column in the database, let's say, "name" you would do
$variable = pdoQuerySingle($pdo, "SELECT name FROM table WHERE id=?", [$id], "name");