如何在WHERE row =(?)SQL php语句中放置多个值

时间:2016-03-07 10:45:41

标签: php mysql sql database

因此,当我手动输入某些值时,我的查询适用于实际的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    | 
------------------------------------------------------------

userID值可能会因用户选择的内容而异,因此可以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,31,但这些内容未正确传递给SELECT STATEMENT。我该如何解决?

由于

2 个答案:

答案 0 :(得分:1)

沿着这些方向的东西

...
 $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。

您将使用call_user_func_array使用可变数量的参数调用bind_param函数。请注意,如果您使用的是PHP 5.6+,则可以执行以下操作:$result->bind_param("i",...$userIDs)

答案 1 :(得分:-1)

select userName from Table where user_id in (1, 2, 3);. 

您可以使用此格式的$ _POST [&#39; userID&#39;]或转换此格式并使用它。