Reputation: 1114
I would want to first check for all equal rows and then put them into a separate table.
This is what I have done so far:
table1
| id | name |
| 1 | JUS |
| 1 | NUM |
| 2 | SET |
/**
* this is the the query for retrieving the data
* from table1
*/
$query="SELECT
id,
name
FROM
table1
order by
id";
$results=$db->query($query);
$previous='';
while($row=mysqli_fetch_assoc($results)){
$id=$row['id'];
$name=$row['name'];
if($id==$previous){
/**
* This is where i am stucked up
*/
$current='';
}
$previous=$id;
}
I want to get the id with 1
as the value into one html table, like below
first html table
ID | 1 | 1 |
Name | JUS | NUM |
and also get the id with 2
as the value into another html table. So in all we will get separate tables
if the id
are not the same:
second html table
ID | 2 |
Name | SET |
Any idea as to how to go about it is appreciated.
Upvotes: 1
Views: 2198
Reputation: 41885
You could just gather all them first in a container, using id
s as your keys so that they'll be grouped together. After that, just print them accordingly:
$data = array();
while($row = $results->fetch_assoc()){
$id = $row['id'];
$name = $row['name'];
$data[$id][] = $name; // group them
}
foreach($data as $id => $values) {
// each grouped id will be printed in each table
echo '<table>';
// header
echo '<tr>';
echo '<td>ID</td>' . str_repeat("<td>$id</td>", count($values));
echo '</tr>';
echo '<tr>';
echo '<td>Name</td>';
foreach($values as $value) {
echo "<td>$value</td>";
}
echo '</tr>';
echo '</table><br/>';
}
This will work if those fields are just like that, if you need something more dynamic, you need another dimension, and instead of just pushing name
, you'll need the push the entire row:
$results = $db->query('SELECT id, name, age FROM table1');
$data = array();
while($row = $results->fetch_assoc()){
$id = $row['id']; unset($row['id']);
$data[$id][] = $row; // group them
}
$fields = array('name', 'age');
foreach($data as $id => $values) {
// each grouped id will be printed in each table
echo '<table>';
// header
echo '<tr>';
echo '<td>ID</td>' . str_repeat("<td>$id</td>", count($values));
echo '</tr>';
foreach($fields as $field) {
// construct td
$temp = '';
echo "<tr><td>$field</td>";
for($i = 0; $i < count($values); $i++) {
$temp .= '<td>' . $values[$i][$field] . '</td>';
}
echo $temp; // constructed td
echo '</tr>';
}
echo '</table><br/>';
}
Upvotes: 3