left join a column with array in php/mysql

Issue

I have several tables 1 contacts and multiple data.

Contacts has an ID field and a Name field; Data has a field called Contacts (as well as other fields).

e.g Contacts

ID - Name
1 - James
2 - Mark
3 - Doug

e.g. data

ID - Contacts - Data
1 - 1,3 - more data
2 - 2 - more data
3 - 2,3,1 - more data

Obviously, the comma-separated numbers link to several people in the contacts table. How can I convert from the comma-separated list to the people’s names? A standard left join won’t work.

Is there a way I can do it in the original query or would I have to add a while inside a foreach inside my original while loop? Such as (the following doesn’t work either but it’s as far as I’ve got):

//original query while {
        $contacts_array = array(implode(",",$db['Contacts'])); 
        foreach ($contacts_array as $contacts_id) 
        { 
            $contacts_query = "SELECT Name FROM data_contacts WHERE ID='$contacts_id'";
            $contacts_result = mysql_query ($contacts_query);
            $contactslist="";
            while($contacts=mysql_fetch_array($contacts_result)){
                $contactslist .= $contacts['Name'].", ";
            } 
        } 
echo $contactslist;
}

Solution

I’ve always stored many-to-many relationships with individual rows instead of comma-separated values:

ID - Contacts
1 - 1
1 - 3
2 - 2
3 - 2
3 - 3
3 - 1

Answered By – Jeff Jenkins

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published