I'm using prepared statements to add rows to my database. I'm restructuring my code and am running into an issue with bind_param - I assume it's syntactical but can't figure out what's wrong.
No data supplied for parameters in prepared statement
function insertRow($fieldNames, $fields, $table, $link) {
$field_names=implode(', ',$fieldNames);
$field_values=implode(', ',$fields);
//add question marks
$q_marks=array();
forEach($fieldNames as &$qm) {
array_push($q_marks, "?");
}
$qs = implode(',',$q_marks);
$stmnt = "INSERT INTO $table ($field_names) VALUES ($qs)";
echo("<br>$stmnt<br>");
$addrow = $link->prepare("INSERT INTO $table ($field_names) VALUES ($qs)");
//add param types (all strings)
$s_chars=array();
forEach($fieldNames as &$s) {
array_push($s_chars, "s");
}
$s = implode('',$s_chars);
echo("$s, $field_values<br>");
$addrow->bind_param($s, $field_values);
try {
echo("adding row...");
$addrow->execute();
} catch(Exception $e){
echo("error: " .$e ."<br>");
return false;
}
}
Trying to use the line
$addrow->bind_param($s, $field_values);
tries to pass a list of the fields joined with commas. This actually supposed to be the value of each value as a separate value. This can easily be done using the splat operator (...
) and the original field values...
$addrow->bind_param($s, ...$fields);
You can also do a few tweaks with other parts of the code, rather than...
$s_chars=array();
forEach($fieldNames as &$s) {
array_push($s_chars, "s");
}
$s = implode('',$s_chars);
you can just use
$s = str_repeat("s", count($fieldNames));