This function is horrible. That long tail of parameters alone! And the lack of prepared statements. And a database related function that decides on its own whether to output an error or not, as though database interaction is something different from other code.
Do yourself a favor, make this function this way
function query($query, $parameters = []) {
$pdo = // here your way of getting a PDO instance.
// DON't TELL ME YOU ARE CREATING A NEW ONE EVERY TIME
if (!$parameters)
{
return $this->query($sql);
}
$stmt = $pdo->prepare($sql);
$stmt->execute($parameters);
return $stmt;
}
This is ALL you need and it's MUCH better than you have at the moment.
Returning a statement is the key. It lets you to attach any fetch method you like to the function call - the most natural way of getting different result types from such a function. Or not to fetch anything at all, if a query happens to be UPDATE or INSERT.
Want a row count?
$count = query("DELETE FROM usars")->rowCount();
want a fetch?
$user = query("select * from users where id=?", [$id])->fetch();
want fetchAll with PDO::FETCH_COLUMN? here you are
$users = query("select name from users")->fetchAll(PDO::FETCH_COLUMN);
Simple, usable, flexible, readable and secure.
If you don't know how to make this function connect only once, here is a link to a simple PDO wrapper I wrote. Note the examples section. It is so exciting that I'd better put it here:
# Table creation
DB::query("CREATE temporary TABLE pdowrapper
(id int auto_increment primary key, name varchar(255))");
# Prepared statement multiple execution
$stmt = DB::prepare("INSERT INTO pdowrapper VALUES (NULL, ?)");
foreach (['Sam','Bob','Joe'] as $name)
{
$stmt->execute([$name]);
}
$id = DB::lastInsertId());
# Getting rows in a loop
$stmt = DB::run("SELECT * FROM pdowrapper");
while ($row = $stmt->fetch())
{
echo $row['name'], PHP_EOL;
}
# Getting one row
$id = 1;
$row = DB::run("SELECT * FROM pdowrapper WHERE id=?", [$id])->fetch();
# Getting single field value
$name = DB::run("SELECT name FROM pdowrapper WHERE id=?", [$id])->fetchColumn();
# Getting array of rows
$all = DB::run("SELECT name, id FROM pdowrapper")->fetchAll(PDO::FETCH_KEY_PAIR);
# Update
$new = 'Sue';
$count = DB::run("UPDATE pdowrapper SET name=? WHERE id=?", [$new, $id])->rowCount();