我正在尝试建立一个动态准备的声明,但我被困在bind_param
部分。我试着阅读引用call_user_func_array
的其他答案,但我无法弄清楚如何在此处进行调整:
//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*/);
}
有没有办法摆脱这种情况。这是我第一次使用这种方法而且我不知道我是否做对了。非常感谢你。
答案 0 :(得分:1)
生成占位符的最简单方法:
function placeholderMarks($count) {
return join(', ', array_fill(0, $count, '?'));
}
将此函数的结果插入到placeholderMarks(count($values_columns))