Help with array, again

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Help with array, again

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

..

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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;
Post Reply