Reputation: 2927
I am trying to build a dynamic prepared statement but I am stuck at the bind_param
part. I tried to read other answers referring to call_user_func_array
but I couldn't figure out how to adapt it here:
//connecting
$connection = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
//info submitted through a form
$values_columns = array(
"column_one" => "value_one", //value_one will be replaced by $_POST['value_one']
"column_two" => "value_two", //value_two will be replaced by $_POST['value_two']
"column_three" => "value_three" //value_three will be replaced by $_POST['value_three']
);
$value_type = implode('', array('s', 's', 's'));
//preparing and binding my query dinamically
function prepare_bind($table_name, $values_columns, $value_type) {
global $connection;
$columns_string = "";
$question_marks = "";
$flag = 0;
$count = count($values_columns);
foreach ($values_columns as $column => $value) {
$flag++;
// building the prepare
if ($flag == $count) {
$columns_string .= $column;
$question_marks .= "?";
} else {
$columns_string .= $column . ", ";
$question_marks .= "?, ";
}
}
$sql = $connection->prepare('INSERT INTO ' . $table_name . ' (' . $columns_string . ') VALUES (' . $question_marks . ')');
$sql->bind_param($value_type, /*I am stuck here while trying to add the values*/);
}
Is there any way to get out of this situation. It is the first time I am using this approach and I don't know if I got it right. Thank you very much.
Upvotes: 1
Views: 107
Reputation: 25336
Easiest solution to generating the placeholders:
function placeholderMarks($count) {
return join(', ', array_fill(0, $count, '?'));
}
Insert the result of this function into the query with placeholderMarks(count($values_columns))
Upvotes: 1