Page 1 of 1

Help with array, again

Posted: Thu Feb 10, 2005 10:58 pm
by s.dot
I need to get a list of IDs from one of my database tables, and then check to see if a given ID # is not in the list of IDs.

I have:

Code: Select all

<?
$sql = "SELECT id FROM my_table";
$query = mysql_query($sql)
$array = mysql_fetch_array($sql);

if(!in_array($id, $array) &#123; die(); &#125;
?>
So, as I know, this only returns one ID. I need a list. So I figured this would work:

Code: Select all

<?
$sql = "SELECT id FROM my_table";
$query = mysql_query($sql)
while($array = mysql_fetch_array($query)) &#123;
$ids = $array&#1111;'id']; &#125;

if(!in_array($id, $ids) &#123; die (); &#125;
But again, the value of $ids is only one ID

Any help here?

Posted: Thu Feb 10, 2005 11:02 pm
by feyd

Code: Select all

SELECT id FROM my_table WHERE id = '$id'
check how many rows are returned (mysql_num_rows()), if any, it exists; if none, it didn't.

..

Posted: Thu Feb 10, 2005 11:07 pm
by s.dot
gotchya, thanks. Arrays have always given me trouble, I guess it's because I try to use them in the wrong situations.

Posted: Thu Feb 10, 2005 11:09 pm
by feyd
your while loop wasn't creating an array to search... just constantly overwriting the same variable. Fixed version:

Code: Select all

$sql = "SELECT id FROM my_table";
$query = mysql_query($sql) or die(mysql_error());
$ids = array();
while($array = mysql_fetch_assoc($query)) &#123;
$ids&#1111;] = $array&#1111;'id']; &#125;

if(!in_array($id, $ids) &#123; die (); &#125;