In building prepared statements for my site, I found that a lot of redundant code could be iterated over. mysqli::prepare
was a pretty straight forward one to iterate, but when I got to mysqli::bind_param
and mysqli::bind_result
, I ran into the following combination of issues:
1) I do not know how many parameters into mysqli::bind_param
2) Using extract(Array)
into the arguments of mysqli::bind_param
will not work, as the arguments for mysqli::bind_param
are passed by reference
3) The EXTR_REF
flag on extract(Array)
won't help either, given that the value of the element passed cannot itself be a reference.
At this point, I've given up and am using eval()
.
$statements[
's_records_by_parent'=>[
'sql'=>
"select * from table where id=?",
'params'=>[
'"i"',
'$id'
]
],
];
foreach($statements as $name=>$statement){
if(!$name=$this->mysql->prepare(
$statement['sql']
))
{
echo"Error preparing statement $name.";
exit;
}
if(!eval("return \$name->bind_param(".implode(',',$statement['params']).");"))
{
echo"Error binding parameters for statement $name.";
exit;
}
}
The above code does exactly what I want it to do, with the exception of having an eval()
statement which is ultimately going to be preparing statements based off of user input, which is concerning to me.