I'm trying to include prepared statements into my code, yet I encountered a problem. Since I don't like the idea to repeat code each time when I need to make simple query I wrote function. Right now with prepared statements it looks like this:
function mysqli_select($conn, $ask, $param, $vars)
{
$arr = [];
$stmt = $conn->prepare($ask);
$stmt->bind_param($param, $vars);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$arr[] = $row;
}
$stmt->close();
return $arr;
}
The problem begins, if the query $ask
contains multiple ?
and there are more than one variable in $vars
. Since I'd like to have this function universal, I need to assume, that I don't know how many $vars
there will be. It's clear to me that $vars
should be a table, but how to pass them properly in bind_param($param, $vars);
?
I'm aware that I need to put there another if
to simplify output of queries that I'll know that will return just one row - this is not a problem.
By the way, does such solution - I mean entire idea of such function - is good practice? In all examples I see that everybody pastes the common parts over and over again. Am I doing something wrong? Was I looking on the wrong examples? No tutorial that I read suggest to do such thing, so perhaps doing this is somehow wrong on the idea, or execution side?