Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to get data from a mysql database... but i only need results specified by an array... for example i have a database which is populated with member data: username, email etc... and another table where i store per member their contact list like... So im looking on a way to display member their contact list... im just not clear on whats the best way... any tips are welcome... for example

$result = mysql_query("select contact_id from member_contact_list");

$contacts = array();

while ($row = mysql_fetch_array($result)){  
   $c_array[] = $row[ 'username' ];
}

$c_array = implode( ',', $existing_users );

$sql = "SELECT * FROM members WHERE id="c_array[]"";

Its a little hard to explain... i hope someone gets what i mean haha

Thanks!

share|improve this question
add comment

4 Answers

up vote 2 down vote accepted

IN will help you like

$sql = "SELECT * FROM members WHERE id IN (".$c_array.")";

Consider that $c_array is an string that consists member id imploded with ,.

share|improve this answer
add comment

Use In

$sql = "SELECT * FROM members WHERE id in (".$c_array.")";

share|improve this answer
 
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. –  Burimi Mar 4 at 12:47
add comment

Using JOIN you can get the contact list of a given member:

SELECT * FROM members AS m
LEFT JOIN
contacts AS c ON (m.user_id = c.user_id)
WHERE m.user_id = 1;

JOINS are efficient then sub-queries

share|improve this answer
add comment

Strange program.

$result = mysql_query("select contact_id from member_contact_list");

$contacts = array(); //**not used anywhere else in the given code**

while ($row = mysql_fetch_array($result)){  
   $c_array[] = $row[ 'username' ]; //**was that supposed to be $contacts?**
   //** also was this the right version: $contacts = $row['id']; ??? **//
}

$c_array = implode( ',', $existing_users ); 
//** where was $existing_users defined? Was that supposed to be $contacts, too?**

$sql = "SELECT * FROM members WHERE id="c_array[]"";
//** correct version is indeed with the clause "WHERE id IN (".$c_array.")" **;

//** last but not least, the $c_array seems to be the collection of user names, not user ids. **//
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.