Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Mysql ("SELECT WHERE ID NOT ")

Tags:

php

mysql

I am trying to exclude the an 'ID' from the Mysql_query but it is still returning the mentioned ID. This ID is '21' but the query returns '21' which is not what I wanted. Did I misspell something in the 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);
}

I print_r'ed the query and it is still returning '21' which I have excluded/or which I thought I did

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 )
like image 262
Belzelga Avatar asked May 02 '13 14:05

Belzelga


3 Answers

There are a couple of problems. Take a look here:

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

$notgallery is currently an array of IDs to check. You need to join them back together with implode, like this:

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

Also, you have wrapped gallery_id's NOT IN value in quotes. So in fact you'd get something like:

"SELECT * FROM `gallery` WHERE `gallery_id` NOT IN ('21, 13')"

Which is like saying WHERE gallery_id != '21, 13'. Presuming you're using INTs for the id column, you need to remove the single quotes around $notgallery. If you are using a string, you can alter your implode:

$notgallery = implode("', '", $id);
like image 168
LeonardChallis Avatar answered Nov 10 '22 00:11

LeonardChallis


$notgallery is an array and in your SQL query you must have a list of id separated by a comma, so try:

$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());
like image 37
Nagasaki Avatar answered Nov 10 '22 02:11

Nagasaki


has above post n better way to put it.

$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());
like image 2
Tarik Filipovic Avatar answered Nov 10 '22 00:11

Tarik Filipovic