将参数动态绑定到 mysqli 语句

Bind parameters dynamically to a mysqli statement

我正在尝试构建一个动态准备语句,但我卡在了 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*/);
}

有什么办法可以摆脱这种情况。这是我第一次使用这种方法,我不知道我是否做对了。非常感谢。

生成占位符的最简单解决方案:

function placeholderMarks($count) {
    return join(', ', array_fill(0, $count, '?'));
}

将此函数的结果插入到带有 placeholderMarks(count($values_columns))

的查询中