Hi, I am trying to convert a helper DB query function I saw in a book to something more versatile. But when the caller provides a prepared statement with named params and its params, I am not sure how to bind them in a function.
If I call queryDB($query, [$name, $age]) with an unnamed-param prepared statement such as $query = INSERT INTO users (name, age) VALUES(?, ?) and $name = "trump; $age = 18, that bindParam code should work.
But there can be times when I (or someone else) will call with a named-param prepared statement such as $query = INSERT INTO users (name, age) VALUES ( :name, :age ) and $name = "trump; $age = 18. The existing bindParam(i, $value) shouldn't work as i refers to some positional param rather than named param but the function wouldn't know those :name, :age, :whatever named parameters. How should I write the bindParam(param, value) to accommodate both named and unnamed prepared statements?
Code:
//this is the original book function I try to update
function queryMysql($query) //it simply submits a query and returns the entire resultset
{
global $connection;
$result = $connection->query($query);
return $result;
}
Code:
///this is my version
function queryDB(string $query, array $param=null) {
global $dbh; //reference the db handle declared in init.php
if (isset($param)) { //query params provided, so a prepared statement
$stmt = $dbh->prepare($query); //prepared statement
for($i = 1; $i <= count($param);$i++) {
$stmt->bindParam(i, $param[$i]);
}
$stmt->execute();
} else { //a straight sql query, not a prepared statement
$stmt = $dbh->query($query);
}
$result = $stmt->fetchAll(); //grab entire resultset
return $result;
}
If I call queryDB($query, [$name, $age]) with an unnamed-param prepared statement such as $query = INSERT INTO users (name, age) VALUES(?, ?) and $name = "trump; $age = 18, that bindParam code should work.
But there can be times when I (or someone else) will call with a named-param prepared statement such as $query = INSERT INTO users (name, age) VALUES ( :name, :age ) and $name = "trump; $age = 18. The existing bindParam(i, $value) shouldn't work as i refers to some positional param rather than named param but the function wouldn't know those :name, :age, :whatever named parameters. How should I write the bindParam(param, value) to accommodate both named and unnamed prepared statements?
Last edited: