所以我的查询适用于实际的 phpmysql
当我手动输入一些值但在 php
中时,服务器我遇到了一些困难。
这是我的SQL
表:
userID | forename | surname | email | age |
------------------------------------------------------------
1 | Jack | Wolf | dj@rave.com | 19 |
2 | Mark | Smith | mark@rave.com | 18 |
3 | Ben | Cas | sex@club.com | 21 |
4 | Jos | Jis | jis@jos.com | 19 |
5 | Luke | Kils | kils@kiss.com | 23 |
------------------------------------------------------------
基本上,我想传递一些UserID
像这样的值 1,3,5
它应该显示:
userID | forename | surname | email | age |
------------------------------------------------------------
1 | Jack | Wolf | dj@rave.com | 19 |
3 | Ben | Cas | sex@club.com | 21 |
5 | Luke | Kils | kils@kiss.com | 23 |
------------------------------------------------------------
用户 ID 值可能会根据用户选择的内容而变化,因此可以是 2
甚至1,2,3,4
甚至1,2,3,4,5
这是我的php
代码:
<?php
require "init.php";
if(!empty($_POST['userID'])){
$userID = $_POST['userID'];
echo $_POST['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");
}
}
?>
当我回显$userID = $_POST['userID'];
时我得到1,2,3
或1
,但是这些没有正确传递到 SELECT STATEMENT
。我该如何修复它?
谢谢
最佳答案
大致上是这样的
...
$userIDs = implode(",",$_POST['userID']); //Array of user ids
$qs = array_fill(0,count($userIds),"?");
$stmt = "SELECT userID, forename, surname, email, age
FROM users
WHERE userID IN (".implode(",",$qs).")";
$bindParams = $userIDs; //Array for the bind parameters
$bindParams = array_unshift($bindParams, "i"); //Prefix with "i"
call_user_func_array([$result, 'bind_param'],$bindParams);
...
这个想法是你的陈述将需要尽可能多的“?”因为有用户 ID,因为您绑定(bind)了那么多整数。
您将使用call_user_func_array
来使用可变数量的参数调用bind_param 函数。请注意,如果您使用 PHP 5.6+,您可以执行以下操作: $result->bind_param("i",...$userIDs)
关于php - 如何在 WHERE row = (?) SQL php 语句中放置多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35841715/