How to fetch data in table group by other column in PHP - php

I have a record like this in database:
section_id description level_id
1 Amethyst 1
2 Betelguise 1
3 Daisy 2
4 Rose 2
I want it to display in my php table just like this:
Level 1
Amethyst
Betelguise
Level 2
Daisy
Rose
Can anyone please help me? I am new at this.
Here's my code:
<table>
<thead>
<tr>
<th>Descriptions</th>
<th>Level</th>
</tr>
</thead>
<?php $sql = "SELECT * FROM tbl_sectiontaken"; ?>
<?php $result = $db->query($sql); ?>
<?php if ($result->num_rows > 0) { ?>
<?php while($row = $result->fetch_assoc()) { ?>
<?php $id = $row['section_id'];
$desc = $row['description'];
$gr = $row['level_id']; ?>
<tbody>
<tr>
<td style="text-transform:capitalized;">
<?php echo $desc; ?>
</td>
<td style="text-transform:capitalized;">
<?php echo $gr; ?>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
But it gives me this result in table:
Descriptions Level
Amethyst 1
Betelguise 1
Daisy 2
Rose 2

You can use group_concat function for this. Use below code if suits your requirements
<?php $sql = "SELECT level_id,GROUP_CONCAT(description) AS description FROM series group by level_id"; ?>
<?php $result = $db->query($sql); ?>
<?php if ($result->num_rows > 0) { ?>
<?php while ($row = $result->fetch_assoc()) { ?>
<?php
$id = $row['section_id'];
$desc = $row['description'];
$gr = $row['level_id'];
$leveArr[$gr][] = $desc;// Create an array with level and description
} } ?>
</tbody>
<table>
<tr><!-- header-->
<?php foreach ($leveArr as $key => $value) { ?>
<td><?php echo "LEVEL " . $key ?></td>
<?php } ?>
</tr>
<tr>
<?php foreach ($leveArr as $key => $value) {
foreach ($value as $key_1 => $data) { ?>
<td><?php
$data = explode(",", $data);
foreach ($data as $key_2 => $final) {
echo $final . "<br>";
}
?></td>
<?php }
} ?>
</tr>
</table>

Updated
Check the sandbox example
Change query with GROUP_CONCAT
SELECT GROUP_CONCAT(if (description ='', null, description)) as description,count(description) as heigher,level_id FROM yourtablename WHERE 1 GROUP BY level_id
And After.They return array like this
$arr=[['description'=>'a,b,c,d','level_id'=>'1','heigher'=>'4'],['description'=>'a,b,c,d','level_id'=>'2','heigher'=>'4']]; ?>
Then Finally Create Table as like this
$sql="SELECT GROUP_CONCAT(if (description ='', null, description)) as description,count(description) as heigher,level_id FROM yourtablename WHERE 1 GROUP BY level_id";
$result = $conn->query($sql);
$arr =[];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
$arr[]=$row;
}
}
<table>
<thead>
<tr>
<?php foreach ($arr as $key => $value): ?>
<th><?='level'.$value['level_id']?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php
$arr = array_filter($arr,function($a=[]){
return $a['level_id'] != 0
}) //filter level not a zero
$h = max(array_map(function($a=[]){
return $a['heigher']; //filter array['heigher only']
},$arr)); // its get the heighest length of description value like [10,15,100]=>100
foreach ($arr as $key => $value){
$value['description'] = !empty($value['description']) ?explode(',',$value['description']):'';
$arr[$key]=$value;
}
?>
<?php for ($i=0; $i < $h[0]; $i++) {?>
<tr>
<?php foreach ($arr as $key => $value): ?>
<th><?=isset($value['description'][$i])? $value['description'][$i] :''?></th>
<?php endforeach; ?>
</tr>
<?php }?>
</tbody>
</table>

Related

Print a html table with transposed data from a multidimensional array

What would be the best way to print an HTML table with an array of arrays in php? Each array key would be the head of the table, and the sub-array items the table cells.
arr = [
key_1 ->
- key_1_val_1
- key_1_val_2
- key_1_val_3
key_2 ->
- key_2_val_1
- key_2_val_2
- key_2_val_3
]
Expected output:
<table>
<tr>
<td>key_1</td>
<td>key_2</td>
</tr>
<tr>
<td>key_1_val_1</td>
<td>key_2_val_1</td>
</tr>
...
</table>
Any idea?
Tnx
Not success:
<table>
<thead>
<tr>
<?php foreach ( array_keys( $get_cards ) as $head ): ?>
<th><?php esc_html_e( get_the_title( $head ) ); ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<tr>
<?php foreach ( $get_cards as $cols ): ?>
<?php $row_end = count( $get_cards ); ?>
<?php $colum_end = count( $cols ); ?>
<?php $count_rows ++; ?>
<?php foreach ( $cols as $col ): ?>
<?php $count_columns ++; ?>
<td>1</td>
<?php endforeach; ?>
<?php if ( $count_rows % 2 === 0 ): ?>
<?php endif; ?>
<?php $count_columns = 0; ?>
<?php endforeach; ?>
<?php $count_rows = 0; ?>
</tr>
</tbody>
</table>
Solved.
This is my solution: https://gist.github.com/angelorocha/bdd10af73d047709553ef225500fe993
The code of your project is to create a new array for creating a comparative table. We can do it by manipulating index in your case.
This is the main logic for creating a new array.
<?php
$i = 0;
$arr = [];
foreach ( $age as $cols ): ?>
<?php
$j = 0;
foreach ( $cols as $vals ):
$arr[$j][$i] = $vals;
$j++;
endforeach;
$i++;
?>
this is the full code.
<!DOCTYPE html>
<html>
<body>
<?php
$age = [
"No"=>["35", "24", "60"],
"Owner"=>["Peter", "John", "David"],
"Location"=>["Hong Kong", "New York", "Los Angeles"]
];
?>
<table>
<thead>
<tr>
<?php
foreach ( $age as $key=>$value ): ?>
<th><?php echo $key; ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<tr>
<?php
$i = 0;
$arr = [];
foreach ( $age as $cols ): ?>
<?php
$j = 0;
foreach ( $cols as $vals ):
$arr[$j][$i] = $vals;
$j++;
endforeach;
$i++;
?>
<?php endforeach;
foreach($arr as $cols):
echo "<tr>";
foreach($cols as $val):
echo "<td>".$val."</td>";
endforeach;
echo "</tr>";
endforeach;
?>
</tr>
</tbody>
</table>
</body>
</html>
Use a set of nested loops to transpose the multidimensional array data (as well as transferring the first level keys as the new first row of data).
Then use a basic loop to print the rows as html. The way implode() is used, it won't matter if the number of columns changes -- it will create as many columns as are needed.
Code: (Demo)
$arr = [
'key_1' => ['A', 'B', 'C'],
'key_2' => ['D', 'E', 'F'],
];
$transpose = [];
foreach ($arr as $k => $row) {
$transpose[0][] = $k;
foreach ($row as $i => $v) {
$transpose[$i + 1][] = $v;
}
}
echo "<table border=1>\n";
foreach ($transpose as $values) {
echo "<tr><td>" . implode('</td><td>', $values) . "</td></tr>\n";
}
echo '</table>';

How to turn a table vertical using PHP

I am just learning PHP ,and I want to create a table that display echo data that I submit to my database , the problem I have that the table displayed horizontally by default as you see Horizontal default table this my script
<table >
<tr>
<th>Name</th>
<th>Age</th>
<th>Height</th>
</tr>
<?php
$conn = mysqli_connect("localhost", "root", "", "class");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Name, Age, Height FROM student order by Name desc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["Name"]. "</td><td>" . $row["Age"] . "</td><td>"
. $row["Height"]. "</td></tr>";
}
echo "</table>";
} else //{ echo "0 results"; }//
$conn->close();
?>
</table>
but I want it to be echoed vertically instead like this VERTICAL RESULT I WANT and I tried to change html in echo in my PHP code but I can't get the result at all and the shape of the table is far away from what I want and this is the full script of my page .
Like everyone else said, you should convert your horizontal array into a vertical one.
Of course it should be a universal function to convert any query result, as opposed to hardcoding the row headings. The idea is to get each row's array keys and use them as the keys for the new array and then add each corresponding value to the new array item.
Here is how it's done in mysqli:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect('127.0.0.1','root','','test');
$mysqli->query("set names 'UTF8'");
$data = [];
$res = $mysqli->query("SELECT Name, Age, Height FROM student order by Name desc");
while ($row = $res->fetch_assoc()) {
foreach(array_keys($row) as $key) {
$data[$key][] = $row[$key];
}
}
and then you get an array with desired structure which you can output using the code from ROOT's answer:
<table border="1">
<?php foreach($data as $key => $val): ?>
<tr>
<td><?= $key ?></td>
<?php foreach($val as $field): ?>
<td><?= $field ?></td>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</table>
I mocked your data into normal array, I used a while loop to create a new Array and create the format that we need to be able to flip the columns into rows, here is what I think you want:
<?php
$users = [
[
'name'=> 'James',
'height'=> 1.75,
'age'=> 18,
],
[
'name'=> 'Bill',
'height'=> 170,
'age'=> 16,
]
];
$newArr = [];
foreach($users as $key => $val) {
$newArr['name'][$i] = $val['name'];
$newArr['age'][$i] = $val['age'];
$newArr['height'][$i] = $val['height'];
$i++;
}
?>
<table border="1">
<?php foreach($newArr as $key => $val): ?>
<tr>
<td><?php echo $key; ?></td>
<?php foreach($val as $field): ?>
<td><?php echo $field; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach ?>
</table>
It's not a good idea ! if you have a lot of ROW you will generate a long table not visible for user in screen.
if you want to do it after all you can change table structure but you will not respect html table structure.
I will give you a
Dirty code
<table>
<tr>
<th>Name</th>
<?php foreach ($row as $value) { ?><td><?php echo$value["Name"]; ?></td>
<?php } ?>
</tr>
<tr>
<th>Age</th>
<?php foreach ($row as $value) { ?>
<td><?php echo $value["Age"]; ?></td>
<?php } ?>
</tr>
<tr>
<th>Height</th>
<?php foreach ($row as $value) { ?>
<td><?php echo $value["Height"]; ?></td>
<?php } ?>
</tr>
</table>
I recommand to USE CSS instead a table

PHP MYSQL Associate array and table

Here is a code.
This loads all the header part (i.e the header for the table) dynamically from the database.
The below code works fine. But the column is mismatched.
i.e. the first row first column of the header is blank and there is a dislocation in the table.
Code
<table border="1">
<?php
$book_query = mysql_query("select * from book_master");
$i = 0;
while($row = mysql_fetch_assoc($book_query))
{
$columns = array_keys($row);
?>
<th>
<?php
foreach($columns as $column)
{
?>
<td><?php echo $column; ?> </td>
</th>
<?php
}
?>
<tr>
<?php
foreach($row as $key=>$value)
{
?>
<td><?php echo $value; ?></td>
<?php
}
?>
</tr>
<?php
$i++;
}
?>
</table>
EDIT:
Here is my print_r($columns) value:
Array ( [0] => Author Name [1] => Book Name [2] => Rating [3] => Location )
I know the problem is with the loop. Could someone help me out?
You can try to change
<th>
<?php
foreach($columns as $column)
{ ?>
<td><?php echo $column; ?> </td>
<?php
}
?>
</th>
to
<tr>
<?php
foreach($columns as $column)
{ ?>
<th><?php echo $column; ?> </th>
<?php
}
?>
</tr>
Just remove TH tag because its create one extra cell, so your layout messed up
<table border="1">
<?php
$book_query = mysql_query("select * from book_master");
$i = 0;
while($row = mysql_fetch_assoc($book_query))
{
if($i == 0){
$columns = array_keys($row);
?>
<?php
foreach($columns as $column){ ?>
<td><?php echo $column; ?> </td>
<?php } ?>
<?php } ?>
<tr>
<?php
foreach($row as $key=>$value){ ?>
<td><?php echo $value; ?></td>
<?php } ?>
</tr>
<?php
$i++;
}
?>
</table>
Hope this will help someone.
Just I have replaced the TH tag with TR and the output is perfect.
<table border="1">
<?php
$book_query = mysql_query("select * from book_master");
while($row = mysql_fetch_assoc($book_query))
{
$columns = array_keys($row);
?>
<tr>
<?php
foreach($columns as $column){ ?>
<td><?php echo $column; ?> </td>
<?php } ?>
</tr>
<tr>
<?php
foreach($row as $key=>$value){ ?>
<td><?php echo $value; ?></td>
<?php } ?>
</tr>
</table>

Need help changing table array by moving a column in PHP

I have been handed the task of making some changes to a PHP webpage that was coded by someone who has left the company and my Php is exactly exeprt.
The page in question displays a database table in a SQL server that allows you to update values via an update page.
Currently the Update function sits under the 'Action' column at the end of the table and I need to relocate the 'Action' column to the start of the table before the 'Name' column.
When I try to make changes, I break the table array and the 'Update' function no longer works.
Current order of columns are;
Name,
Value,
Details,
Action
The new order of columns attempting to achieve
Action,
Name,
Value,
Details
I have also included the code in question.
Any assistance would be appreciated
Note** It is a Php website running on a Windows box and connecting to a MSSQL Server 2008
$query = sqlsrv_query($conn, 'SELECT * FROM Database_Values ORDER BY Name ASC');
// Did the query fail?
if (!$query) {
die( FormatErrors( sqlsrv_errors() ) );
}
// Dump all field names in result
$field_name = "";
foreach (sqlsrv_field_metadata($query) as $fieldMetadata) {
foreach ($fieldMetadata as $name => $value) {
if ($name == "Name") {
$field_name .= $value . '-';
}
}
}
$field_name = substr_replace($field_name, "", -1);
$names = explode("-", $field_name);
?>
<div style="max-height:610px; overflow:auto;">
<table border="1" cellspacing="0" cellpadding="0" bordercolor="#ccc" class="table" width="100%">
<tr>
<?php
foreach ($names as $name) {
?>
<th><?php echo $name; ?></th>
<?php
}
?>
<th>Action</th>
</tr>
<?php
// Fetch the row
while ($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
//print_r($row);
?>
<tr>
<?php
foreach ($row as $key => $eachrow) {
?>
<td nowrap="nowrap">
<?php echo $eachrow; ?>
</td>
<?php
}
?>
<td nowrap="nowrap">
<?php $groupid = $_SESSION["gid"] ;
if($groupid!='1') {
?>
<a href="javascript:void(0);" title="Permission Restricted" >Update</a>
<?php } else { ?>
Update
<?php } ?>
</td>
</tr>
<?php
}
?>
</table>
</div>
All you need to do is change the order of the th and td cells in the html
$query = sqlsrv_query($conn, 'SELECT * FROM Database_Values ORDER BY Name ASC');
// Did the query fail?
if (!$query) {
die( FormatErrors( sqlsrv_errors() ) );
}
// Dump all field names in result
$field_name = "";
foreach (sqlsrv_field_metadata($query) as $fieldMetadata) {
foreach ($fieldMetadata as $name => $value) {
if ($name == "Name") {
$field_name .= $value . '-';
}
}
}
$field_name = substr_replace($field_name, "", -1);
$names = explode("-", $field_name);
?>
<div style="max-height:610px; overflow:auto;">
<table border="1" cellspacing="0" cellpadding="0" bordercolor="#ccc" class="table" width="100%">
<tr>
<th>Action</th>
<?php
foreach ($names as $name) {
?>
<th><?php echo $name; ?></th>
<?php
}
?>
</tr>
<?php
// Fetch the row
while ($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
//print_r($row);
?>
<tr>
<td nowrap="nowrap">
<?php $groupid = $_SESSION["gid"] ;
if($groupid!='1') {
?>
<a href="javascript:void(0);" title="Permission Restricted" >Update</a>
<?php } else { ?>
Update
<?php } ?>
</td>
<?php
foreach ($row as $key => $eachrow) {
?>
<td nowrap="nowrap">
<?php echo $eachrow; ?>
</td>
<?php
}
?>
</tr>
<?php
}
?>
</table>
</div>

Show only MySQL columns that exist in queried table

I have several MySQL tables that are dynamically generated into a html table one table at a time through the code below. However, the tables don't have the same columns. i.e. One table has a description column, whereas the other does not.
Is the following code the best way to have all the possible MySQL columns among the various tables in the script but only show the MySQL columns that exist for the selected table? I feel like I'm redundant by writing "isset" for every column. Thanks!
<?php
$query = " SELECT * FROM $tablename ";
$query_select = mysqli_query($con,$query);
while($row = mysqli_fetch_array($query_select)) {
?>
<table>
<tr>
<?php if(isset($row['name'])){ ?>
<td><?php echo $row['name'];?></td>
<?php } ?>
<?php if(isset($row['description'])){ ?>
<td><?php echo $row['description']?></td>
<?php } ?>
</tr>
</table>
You might want to make your code adapt to the fields in the result set:
<?php
$result = mysqli_query($con,$query);
$fields = mysqli_fetch_fields($result);
$myaliases = array(
'column_id' => 'id'
);
?>
<table>
<tr>
<?php foreach ($fields as $field): ?>
<th><?php echo $myaliases[$field->name] ?: $field->name; ?></th>
<?php endforeach; ?>
</tr>
<?php while($row = mysqli_fetch_array($result)): ?>
<tr>
<?php foreach ($fields as $field): ?>
<td><?php echo $row[$field->name]; ?></td>
<?php endforeach; ?>
</tr>
<?php endwhile; ?>
</table>
Re comments:
I've added code above to print a table row for column headings.
I've also included an example of mapping a field name column_id to a table heading id in the output. If I define no alias for a given column, it defaults to the original field name by using the PHP 5.3 operator ?:
You could alternatively define column aliases in your SQL query like SELECT column_id AS id ...
See http://www.php.net/manual/en/mysqli-result.fetch-fields.php
You can foreach the array instead.
<?php
$query = " SELECT * FROM $tablename ";
$query_select = mysqli_query($con,$query);
?>
<table>
<?php while($row = mysqli_fetch_array($query_select, MYSQLI_ASSOC)) { ?>
<tr>
<?php foreach($row as $key => $value) { ?>
<td><?=$value?></td>
<?php } //Endforeach ?>
</tr>
<?php } //Endwhile ?>
</table>
If you need to print labels you can also use an associative array and an additional iteration to do that as well.
<?php
$query = " SELECT * FROM $tablename ";
$keys = array('name' => 'Name Label', 'description' => 'Description Label');
$query_select = mysqli_query($con,$query);
$i = 0;
?>
<table>
<?php while($row = mysqli_fetch_array($query_select, MYSQLI_ASSOC)) { ?>
<?php if($i == 0) { ?>
<tr>
<?php foreach($row as $key => $value) { ?>
<td><b><?=$keys[$key]?></b></td>
<?php } //Endforeach ?>
</tr>
<?php } $i++; //Endif ?>
<tr>
<?php foreach($row as $key => $value) { ?>
<td><?=$value?></td>
<?php } //Endforeach ?>
</tr>
<?php } //Endwhile ?>
</table>
You could just loop through the results. However, that would not perform any checks. Most likely, you'll have to do something like this, depending on what you're actually getting from the database.
<?php foreach ($row as $field): ?>
<?php if ($field): ?>
<td><?php echo $field; ?></td>
<?php endif; ?>
<?php endforeach; ?>
Edit: In keeping in line with the comment you added above, you could simply remove the if clause.
not sure if this is what you need,
but you can use indexes instead for the column instead of names:
<?php
$query = " SELECT * FROM $tablename ";
$query_select = mysqli_query($con,$query);
while($row = mysqli_fetch_array($query_select)) {
echo $row[0] ." ".$row[1]." ".$row[2]
}
?>
mysql_fetch_array
possible formating:
<table>
<?php
$query = " SELECT * FROM $tablename ";
$query_select = mysqli_query($con,$query);
while($row = mysqli_fetch_array($query_select)) { ?>
<tr>
<?php for(var $i=0; $i < count($row); $i++){
echo "<td>". $row[i] ."</td>";
} ?>
</tr>
<?php } ?>
</table>

Categories