【发布时间】: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生成一个问号数组。 -
implode是join的别名。 -
可能很有趣,以便您可以看到逻辑? github.com/aaronlord/mysqli。 (我在这里工作)。另外,互联网搜索:
'github mysqli class'其他课程。
标签: php mysqli prepared-statement bindparam