0

I'm creating a small website using PHP, which is generally a site for showcasing the hospital, and I modified the code given in this example: https://www.w3schools.com/php/php_mysql_select.asp

<?php
    $query = "SELECT * FROM emp WHERE type = 'woman' "; 
    $result = mysqli_query($db, $query);
    if(mysqli_num_rows($result) > 0)
    { 
        while($row = mysqli_fetch_array($result)) 
        {
            $cat = $row["cat"] . ','; 
            echo $cat;                
           ////<---- echo on while (Loop)
         }
     }

The expected output would be as follows:

Output: 35,36

But I changed the code with the link above and it is as follows:

if(mysqli_num_rows($result) > 0)
{ 
  while($row = mysqli_fetch_array($result)) 
  {
    $cat = $row["cat"] . ','; 
  }
  echo $cat;              
  ///// <---- echo Out of While (Loop)
} 
Output: 35

My expecting output would be 35, 36 outside of "while" using "echo".

What code do you recommend to output "35,36" the same code above?

Bob Dalgleish
  • 8,167
  • 4
  • 32
  • 42
itlearn
  • 45
  • 4
  • If an answer solved your problem, consider accepting the answer. Here's how http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work then return here and do the same with the tick/checkmark till it turns green. This informs the community, a solution was found. Otherwise, others may think the question is still open and may want to post (more) answers. You'll earn points and others will be encouraged to help you. *Welcome to Stack!* – Jay Blanchard Jan 14 '20 at 12:46
  • Strange, as I'd expect the `$cat` variable to be clobbered upon each loop, and the output to be `36,` in your second example. (Then again there is no order clause.) – Progrock Jan 14 '20 at 12:55

1 Answers1

3

You can try the below code to achive your requirement

$data = array();

if(mysqli_num_rows($result) > 0)
{ 
  while($row = mysqli_fetch_array($result)) {
    $data[] = $row["cat"];
  }
} 

echo implode(",",$data);
Ajith
  • 2,476
  • 2
  • 17
  • 38
  • 1
    Please do not harass the OP to accept your answer in the first few seconds. It is possible that another better answer may come along which actually tries to educate the OP. – mickmackusa Jan 14 '20 at 13:06