我正在编写一个带三个参数的函数,前两个参数是字符串,但我希望第三个参数包含多个参数。 下面是代码块
function myFetch($query, $datatype, $variables){
include("models.php");
$stmt = $conn->prepare($query);
$stmt->bind_param($datatype, $variables);
$stmt->execute();
$result = $stmt->get_result();
return $result->fetch_assoc();
$stmt->close();
$conn->close();
}
从上面的代码中,我希望第三个参数$variable
包含其他参数,例如$variable = $one, $two, $three, $four
,其中这些参数有自己的数据传递给{{1}功能。
bind_param
,$query
和$datatype
的示例:
$variables
$query = "SELECT * FROM table WHERE id = ? and visible = ?";
$datatype = "ii";
$id = 1,$visible = 1;
答案 0 :(得分:2)
解决方案是这样的:
$param
数组,并使用$variables
循环遍历参数变量数组for
。$variables
数组作为参考。array_unshift()
功能将$datatype
推送到$variables
阵列的开头。call_user_func_array()
函数绑定每个参数。所以你的myFetch()
函数应该是这样的:
function myFetch($query, $datatype, $variables){
include("models.php");
$stmt = $conn->prepare($query);
$param = array();
$count = count($variables);
for($i = 0; $i < $count; ++$i){
$param[] = &$variables[$i];
}
array_unshift($param, $datatype);
call_user_func_array(array($stmt, 'bind_param'), $param);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
$conn->close();
return $result;
}
随后,您可以像这样调用此函数:
$query = "SELECT * FROM table WHERE id = ? and visible = ?";
$datatype = "ii";
$variables = array(1, 1);
$result = myFetch($query, $datatype, $variables);
while($row = $result->fetch_assoc()){
// display $row details
}
答案 1 :(得分:2)
这应该在你的功能中做你想做的一切:
$query = "SELECT * FROM table WHERE id = ? and visible = ?";
$variables = array($id, $visible);
function myFetch($query, $variables){
include("models.php");
$stmt = $conn->prepare($query);
$stmt->execute($variables);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
只是一些想法:
答案 2 :(得分:1)
使用Reflection来呼叫mysqli::bind_param()
,例如:
<?php
$resource = $db->prepare("SELECT * FROM table WHERE id = ? and visible = ?");
$reflectionArray = array(1,"yes");
$reflection = new ReflectionClass('mysqli_stmt');
$method = $reflection->getMethod("bind_param");
$method->invokeArgs($resource, $reflectionArray);
$resource->execute();
?>
你的职能:
function myFetch($query, $datatype, $variablesArray){
include("models.php");
$stmt = $conn->prepare($query);
$reflection = new ReflectionClass('mysqli_stmt');
$method = $reflection->getMethod("bind_param");
$method->invokeArgs($stmt, $variablesArray);
$resource->execute();
$result = $stmt->get_result();
$stmt->close();
$conn->close();
return $result->fetch_assoc();
}