0

For example I have MySQL two tables, Category and Student.

---------------------
| id_cat | name_cat  |
----------------------
|  1     | language  |
|  2     | math      |
|  3     | science   |
---------------------  

---------------------------------------
| id_student | name_student | id_cat  |
---------------------------------------
|      1     | Peter Parker | 2, 3    |
|      2     | Tony Stark   | 1, 2, 3 |
|      3     | Bruce Wayne  | 3       |
---------------------------------------

Then I tried with this code line :

$check=mysqli_query($conn, "SELECT * FROM student LEFT OUTER JOIN category ON student .id_cat = category.id_cat ORDER BY id_student ASC");
while($data=mysqli_fetch_array($check)){ 
    $namestudent = $data['name_student'];
    $namecat = $data['name_cat'];
    echo ''.$namestudent.' : '.$namecat.'';
}

But the result is
Peter Parker : math
Tony Stark : language
Bruce Wayne : science

According to table, the right output is
Peter Parker : math, science
Tony Stark : language, math, science
Bruce Wayne : science

Dharman
  • 30,962
  • 25
  • 85
  • 135
oyotsuket
  • 39
  • 6

1 Answers1

-2

Issue is your id_cat table in student contains multiple ids which are in string.Single Query will not match all ids in single tuple. Here its the solution;

 $check=mysqli_query($conn, "SELECT * FROM student");
  while($data=mysqli_fetch_array($check))
  { 

    $namestudent = $data['name_student'];
    $namecat = $data['name_cat'];
     $checking=explode(',',$data['id_cat']) =>this is give [0]=2,[1]=3,So on.....
     for($i=0;$i=count($checking);$i++)
    {
      $check1=mysqli_query($conn, "SELECT * FROM category where id_cat='$checking[$i]'");
      while($result=mysqli_fetch_array($check))
      {
        echo $result['name_category];
      }
     }
   }