基本上,我有一个名为$userID = $_POST['userID'];
的变量。现在,这只能取一个值。
但我希望它尽可能采用多个值,例如$userID = 1,2,4,5
或$userID = 2
甚至$userID = 1,2,3,4,5,6,7
我不知道如何为多个号码执行此操作,但这是我的php
脚本:
<?php
require "init.php";
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs \n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "\n";
}
}
if(!empty($_POST['userID'])){
$userID = $_POST['userID'];
$userID = foo($userID);
$stmt = "SELECT userID, forename, surname, email, age
FROM users
WHERE userID IN (?)";
$result = $conn-> prepare($stmt);
$result->bind_param('i', $userID);
$result->execute();
$outcome=$result->get_result();
$response = array();
if(($outcome->num_rows)>0){
while($row = $outcome->fetch_assoc()){
$response[] = array
(
"userID" => $row["userID"],
"forename" => $row["forename"],
"surname" => $row["surname"],
"email" => $row["email"],
"age" => $row["age"]
);
}
echo json_encode($response);
}
else{
echo json_encode("None found");
}
}
?>
编辑:使用上面的代码,我不断得到:
Number of arguments: 1
Argument 0 is: 1,2,3
"Failed"
- 如果$userID = 1,2,3
因此,您可以看到userID
只能获取1个值,但我想在某些情况下采用多个。如何转换它以便需要很多。
这是我坚持的唯一一点,因为当我为SQL
提供硬编码值时phpmyadmin
内容的其余部分正常工作
答案 0 :(得分:0)
您可以使用call-user-func-array
例如:
$userID = "1,2,3,4,5,6,7";
call-user-func-array(function_name, explode(',', $userID));
如果您使用的是php 5.6&gt;,那么您可以使用...
可变参数函数。
根据你的评论,
您可以使用func_get_arg。
修改示例
<?php
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs \n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "\n";
}
}
foo($userID);
?>