简体   繁体   中英

Get and Display all the value from mysql with the same type in php

I'm setting a php and mysql i have this table in my db

id  type    details 
1   1   sample details
2   1   
3   1   
4   2   
5   2   
6   2   
7   3   
8   3   
9   3   
10  1   
11  1   
12  1   
13  5   

already tried this

sql = 'SELECT id, GROUP_CONCAT(type) as concat FROM ob GROUP BY type';

     $result = mysqli_query($db, $sql);
    while($row = mysqli_fetch_assoc($result)) {
        $final[] = explode(',', $row["concat"]);
    }

    print_r($final);

pls help me HOW CAN I DISPLAY this sample output (in html)

type   id
1      1 2 3 11 12
2      4 5 6
3      6 7 8 
5      13

i already tried some foreach loop but it seem i cant get this result.

You should try it :

foreach($sql_result as $type=> $id){

  if(!isset($res[$type])){
    $res[$type]=array();
  }
  array_push($res[$type], $id);
}

This give an array like this :

[1] => { [0] => [1], [1] => [2], [2] => [3], [4] => [11]}

Now you should use another foreach loop to output the result

foreach($res as $type => $arr){
  echo $type;
  foreach($arr as $id){
    echo $id."<br>;
  }
}

Have fun :)

$x = '';

while($row = mysqli_fetch_assoc($result)){

if($x == $row['x']){do something} else {do something else};
$x = $row['x'];
}

Please try this query and fetch the record;

 $sql = 'SELECT type,GROUP_CONCAT(id SEPARATOR ' ') as id FROM ob GROUP BY type';
$result = mysqli_query($db, $sql);
echo "<b>type</b>&nbsp;&nbsp;<b>id</b><br/>";
while($row = mysqli_fetch_assoc($result)) {
    echo $row['type'] ."".$row['id']."<br/>";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM