0

I have saved some values as comma separated in table 1 column.

I want to fetch all rows containing values from table 2 where these comma separated values are.

But my current code is fetching only one row with first value.

Tables structure is like below :

Table 1

id   |  faculties           | another_field
1    |  DFGHFGD1,ERTGDFGE2  | xyzxyzxyz

Table 2

id   |  unique_id   | full_name
1    |  DFGHFGD1    | AAA AAA
2    |  THOGHFGD1   | BBB BBB
3    |  ERTGDFGE2   | CCC CCC
4    |  LLMNBHUH1   | DDD DDD
5    |  HGFGDHHD3   | EEE EEE
6    |  RGDJHFGN4   | FFF FFF
7    |  PLYHTGGD1   | HHH HHH

Now I want to fetch both rows with unique_id = DFGHFGD1 And ERTGDFGE2 in Table 2.

I tried following code. But it is fetching only first value(DFGHFGD1) row.

 <?php 
        $faculty ="DFGHFGD1,ERTGDFGE2"; // Fetch with another query for table 1
        $var = explode(",", $faculty );
        ?>
          <ol>
           <?php
             foreach($var as  $value){
             $fquery = "select * from table_2 where unique_id = '$value'";          
             $result = $database->get_results($fquery);
                foreach($result as $data){
            ?> 
                <li><?php echo $data['full_name'];?></li>
            <?php }  ?>
          </ol>
  <?php } ?>

Result should be like

  1. AAA AAA
  2. CCC CCC

But I am Getting only

  1. AAA AAA
6
  • "I have saved some values as comma separated in table 1 column." -- Big mistake! Read "Is storing a delimited list in a database column really that bad?" and normalize the schema. Commented May 4, 2020 at 11:36
  • Are you sure the </ol> is in the right place, should it be outside both the foreach() loops? Commented May 4, 2020 at 11:38
  • @stickybit should I save values in table 1 with comma separate in separate mysql table in rows ? Commented May 4, 2020 at 11:38
  • @NigelRen I changes place of <ol> and </ol> and tried just now but same result Commented May 4, 2020 at 11:40
  • @darshan: Yes, exactly. Commented May 4, 2020 at 12:01

1 Answer 1

1

<ol> Tag will be outside of first foreach loop.

Correct code will be :

<?php 
$faculty ="DFGHFGD1,ERTGDFGE2";
$var = explode(",", $faculty);
?>
<ol>
<?php
foreach($var as $value) {
  $fquery = "select * from `table_2` where `unique_id` = '$value'"; 
  $result = $database->get_results($fquery);
  foreach($result as $data){ ?>
    <li><?php echo $data['full_name']; ?></li>
  <?php 
  } 
}
?></ol>
Sign up to request clarification or add additional context in comments.

1 Comment

Code-only answers are discouraged. Please click on edit and add some words explaining how your code addresses the question. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.