Php Mysql NOT IN array only affecting first result in array

烈酒焚心 提交于 2019-12-11 07:45:37

问题


So I have a query to create an array of ID's that I do not want to be included in the data that populates my Select List. Both the select list and the array of excluded ID's are being pulled from a mysql database. The problem I am having is that when I echo out $exclude, it appears correctly in a comma separated list (1,2,3). However, when I attempt to add it in my NOT IN statement, it is only excluding the first number. I need it to exclude the entire array. Any ideas?

<?php
$excludeSql = "SELECT member_id FROM appointments WHERE joint_id = '$jointid'";
$excludeData = mysql_query($excludeSql, $link);
while($excluderow = mysql_fetch_array($excludeData)){

    $excludearray[] = $excluderow['member_id'];

                              }
$exclude = implode(',',$excludearray);
echo $exclude;
?>
<select name="attendees[]">             
    <option value="">--Select--</option>

        <?php 
        $memberSql = "SELECT id, firstName, lastName FROM members WHERE id NOT IN('".$exclude."') && compid = '$compid' ORDER BY lastName ASC";
        $memberResult = mysql_query($memberSql, $link);
            while($memberRow = mysql_fetch_assoc($memberResult)){?>
                <option value="<?php echo $memberRow['id'];?>" ><?php echo "".$memberRow['lastName'].", ".$memberRow['firstName'].""; ?></option>
        <?php } ?>              
</select> 

回答1:


You don't need the quote here:

WHERE id NOT IN('".$exclude."')
                ^            ^

Also you could achieve the same result in one query:

SELECT 
  id, 
  firstName, 
  lastName 
FROM members 
WHERE id NOT IN
  (SELECT 
     member_id 
   FROM appointments 
   WHERE joint_id = '$jointid')



回答2:


You quoted your exclude IDS, so you've turned that comma separated list of numbers into a monolithic string:

WHERE id NOT IN ('1,2,3,4')
WHERE id NOT IN (1,2,3,4)

The above two are two completely DIFFERENT statements. One is a single string, which makes it the equivalent of id <> '1,2,3,4'. The other is a list of 4 numbers for the IN operation.



来源:https://stackoverflow.com/questions/25632137/php-mysql-not-in-array-only-affecting-first-result-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!