【问题标题】:Bind parameters dynamically to a mysqli statement将参数动态绑定到 mysqli 语句
【发布时间】:2015-12-16 20:08:22
【问题描述】:

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

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

【问题讨论】:

  • 您最好使用一个值数组,然后使用join(', ', $arr) 以避免尾随逗号。您可以使用array_fill 生成一个问号数组。
  • implodejoin 的别名。
  • 可能很有趣,以便您可以看到逻辑? github.com/aaronlord/mysqli。 (我在这里工作)。另外,互联网搜索:'github mysqli class' 其他课程。

标签: php mysqli prepared-statement bindparam


【解决方案1】:

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

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

placeholderMarks(count($values_columns))将这个函数的结果插入到查询中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-04
    • 2020-12-11
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    相关资源
    最近更新 更多