PHP: Mysql ("SELECT WHERE ID NOT ")

5

我试图从Mysql_query中排除一个“ID”,但它仍然返回所提到的ID。 这个ID是“21”,但查询返回的却是“21”,这不是我想要的结果。 我在Mysql中有拼写错误吗?

("SELECT * FROM `gallery` WHERE `gallery_id` NOT IN ('$notgallery')") or die (mysql_error());


function not_gallery($pic){

$pic = $_GET['id'];
$id = explode(".", $pic);
$notgallery = $id;

$notg = mysql_query("SELECT * FROM `gallery` WHERE `gallery_id` NOT IN ('$notgallery')") or die (mysql_error());
while($not_row = mysql_fetch_assoc($notg)){
    $notgimage[] = array(
        'id' => $not_row['gallery_id'],
        'user' => $not_row['user_id'],
        'name' => $not_row['name'],
        'timestamp' => $not_row['timestamp'],
        'ext' => $not_row['ext'],
        'caption' => $not_row['caption'],

    );
}
print_r($notgimage);
}

我使用print_r打印出查询结果,仍然返回“21”,这是我排除掉的或者我认为我已经排除掉了的。

Array ( [0] => Array ( [id] => 21 [user] => 18 [name] => NotDeojeff [timestamp] => 1367219713 [ext] => jpg [caption] => asd ) [1] => Array ( [id] => 22 [user] => 18 [name] => NotDeojeff [timestamp] => 1367225648 [ext] => jpg [caption] => Ogre magi )

数组([0] => 21 [1] => jpg)21.jpg - Belzelga
2
你正在传递explode的结果,它会给你一个数组。你需要再次使用逗号作为粘合剂来进行implode操作。 - andrewsi
$notgallery 是一个数组。我假设不需要 .jpg 扩展名,所以我认为你的意思是 "WHERE gallery_id != {$notgallery[0]}" - gen_Eric
2
此外,您引用了传递给IN的字符串;这意味着您只会匹配整个字符串,而不是单个值。IN ('12,21')IN(12,21)不同。 - andrewsi
1
当某个 SQL 查询不符合你的预期时,总是打印出该查询并检查是否一切正常。 - nacholibre
显示剩余3条评论
3个回答

9

有几个问题需要解决。请看这里:

"SELECT * FROM `gallery` WHERE `gallery_id` NOT IN ('$notgallery')"

$notgallery目前是一个需要检查的ID数组。您需要使用implode将它们重新连接起来,像这样:

```php implode(',', $notgallery) ```
$notgallery = implode(', ', $id);

此外,您将gallery_id的NOT IN值用引号包裹起来。因此,实际上您会得到类似以下的结果:
"SELECT * FROM `gallery` WHERE `gallery_id` NOT IN ('21, 13')"

这句话的意思就像是说 WHERE gallery_id != '21, 13'。假设您使用 id 列的 INT 类型,您需要去掉 $notgallery 周围的单引号。如果您正在使用字符串,则可以修改您的 implode:

$notgallery = implode("', '", $id);

4

$notgallery是一个数组,在你的SQL查询中,你必须有一个以逗号分隔的id列表,所以请尝试:

$pic = $_GET['id'];
$id = explode(".", $pic);
$notgallery = $id;
$notgallery = implode(",", $notgallery);
$notg = mysql_query("SELECT * FROM `gallery` WHERE `gallery_id` NOT IN ($notgallery)") or die (mysql_error());

3
$notgallery = str_replace('.', ',', $pic); 这样写会更有意义吧? - gen_Eric

2
有更好的方法来表示上面的帖子。
$pic = $_GET['id'];
$id = explode(".", $pic);
$notgallery = $id;
$notgallery = implode(",", $notgallery);
$notg = mysql_query("SELECT * FROM `gallery` WHERE `gallery_id` NOT IN ($notgallery)") or die (mysql_error());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接