How to write a secure SELECT query which has a variable number of user-supplied values with mysqli?

后端 未结 2 1736
故里飘歌
故里飘歌 2020-12-02 03:02

I would like some help to execute a foreach into my code.

I post multiple value into username : as username[0] = user1 , user2

but my foreach gi

2条回答
  •  無奈伤痛
    2020-12-02 03:25

    Remove the '$value = $username_grab;' inside the foreach

    i.e.

    foreach ($username_grab as $value){
        // $value = $username_grab;   This does not belong
    

    If that doesn't help, can you show the code this POSTs from and do a

    print_r($username_grab)
    

    just after you set it

    Edit

     user1,user2 )
    // $username = implode(",", $username_grab);                    // implode turns an array into a string using a delimiter
    $usernames = explode(",", $username_grab[0]);                   // explode turns a string into an array by delimiter. The [0] index is for the post coming through as such
    // $usernames should now look something like this. This is the array you will be working with
    // Array ( [0] => user1, [1] => user2 )
    
    foreach($usernames AS $value)
    {
        $sql = "select * from linked_user where username = '" . mysqli_escape_string($value) . "' and company_name = '" . mysqli_escape_string($companyname) . "'"; // SQL injection is a threat. Seperate issue to look into   
        $res = mysqli_query($conn,$value);
        $cnt = 0;                                                   // Looking for multiple results. Counter for array
        while($row = mysqli_fetch_array($res))
        {
            $returnValue[$cnt]['username'] = $row['username'];      // Create a two dimensional array (multiple users. Each has their own index then
            $returnValue[$cnt]['user_scid'] = $row['user_scid'];    // Can replace the $cnt field with $row['userid'] (or whatever) if you have a primary key on the table i.e. $returnValue[$row['userid']]['username'] = $row['username'];
        }
        $cnt++;                                                     // Increase the counter for the next user
    }
    
    // $returnValue should now look something like this
    // Array ( 
    // [0] => Array (
    //          ['username'] => 'user1', 
    //          ['user_scid'] => 'whateverthedbsaysforuser1'),
    // [1] => Array (
    //          ['username'] => 'user2', 
    //          ['user_scid'] => 'whateverthedbsaysforuser2'),
    // )
    echo json_encode($returnValue);
    ?>
    

提交回复
热议问题