Tao
Tao

Reputation: 85

SELECT column values from database table rows where the ID is found in a whitelist array

I have this code above which I use to implode some variable. The issue is that I need to create the same thing for $hostess_name[] as I did for $hostess_id_selected[]. I don't know what am I doing wrong. I need to implode it the same way as I did with $hostess_id_selected1

 foreach($hostess_id as $val) {
   $hostess_id_selected[] = $val;
   $sqlnomehostess="SELECT nome_hostess FROM hostess where id='$val'";
   $resultnomehostess=mysql_query($sqlnomehostess)or die(mysql_error());
   $hostess_name= array();

   while ($row=mysql_fetch_array($resultnomehostess,MYSQL_ASSOC)) {
     $hostess_name[] = $row['nome_hostess'];
   }
 }

 $hostess_id_selected1 = implode("-",$hostess_id_selected);

Upvotes: 0

Views: 96

Answers (2)

Vijay Verma
Vijay Verma

Reputation: 3698

implode is a basic function of php. It always work perfect. Just check your array $hostess_id_selected, what it returning. I think it will help you.

Upvotes: 0

galchen
galchen

Reputation: 5290

you have $hostess_name= array(); inside the loop. move it above

EDIT:

some tips:

 foreach($hostess_id as $val) {
   $hostess_id_selected[] = $val;
 // this is pointless, i mean - you are recreating $hostess_id

btw, just a little tip for improvement - instead of running many SQL queries you can use a single query:

$sql = "SELECT GROUP_CONTACT(`nome_hostess` SEPARATOR '-') AS name_list 
        FROM `hostess` 
        WHERE id IN (".implode(',',$hostess_id).")";

if the items in $hostess_id are not necessarily numeric:

$sql_ids = array();
foreach($hostess_id as $id)
    $sql_ids[] = mysql_real_escape_string($id);
$sql = "SELECT GROUP_CONTACT(`nome_hostess` SEPARATOR '-') AS name_list 
        FROM `hostess` 
        WHERE id IN (".implode(',',$sql_ids).")";

and after that:

the sql query returns 1 row with a column called "name_list", which contains the names joined with "-".

if you want to maintain the order of the id and name - you should do:

$sql = "SELECT 
             GROUP_CONTACT(`nome_hostess` SEPARATOR '-') AS name_list,
             GROUP_CONTACT(`id` SEPARATOR '-') AS id_list 
        FROM `hostess` 
        WHERE id IN (".implode(',',$hostess_id).")";

Upvotes: 2

Related Questions