This question already has an answer here:
MySql Transpose Row into Column and Column into Row [duplicate]
(1 answer)
Closed 7 years ago.
I want to display rows as columns.
This is mysql table called Term
|Name ||Year ||HTML ||CSS ||Js ||
|Year1 ||2013-08-30||90 ||70 ||70 ||
|Year2 ||2014-08-30||100 ||65 ||80 ||
|Year3 ||2015-08-30||80 ||95 ||90 ||
What I want is to display as columns like this
|Subject||Year1 ||Year2 ||Year3 ||
|HTML ||90| ||100 ||80 ||
|CSS ||70| ||65 ||95 ||
|JS ||70| ||80 ||90 ||
Code
<tr>
<th>Code</th><th>Subject</th><th>year1</th>
<th>year2</th><th>year3</th>
</tr>
<?php
$query = mysql_query("SELECT * FROM term WHERE Stdid='$id'");
while ($row = mysql_fetch_assoc($query)) {
foreach($row as $key => $value) {
?>
<tr>
<th><?php echo $key ?></th>
<th><?php echo $value?></th>
<th>99</th><th>00</th>
</tr>
<?php } } } ?>
</table>
My result only works for the first year
|Subject||Year1 ||Year2 ||Year3||
|HTML ||90| ||? ||? ||
|CSS ||70| ||? ||? ||
|JS ||70| ||? ||? ||
You first need to transpose all data in a temporary array before you can output it again. I'll give you 2 methods to do this.
Method 1: just fetch every row and switch the row index by the column index:
<table>
<tr>
<th>Subject</th>
<th>year1</th>
<th>year2</th>
<th>year3</th>
</tr>
<?php
$mysqli = new mysqli('localhost', 'user', 'pass', 'database');
$id = 1;
$report = array();
$columnIndex = 0;
$query = $mysqli->query("SELECT HTML, CSS, Js FROM term WHERE Stdid='$id'");
while ($results = $query->fetch_assoc()) {
foreach ($results as $course => $score) {
$report[$course][$columnIndex] = $score;
}
$columnIndex++;
}
foreach ($report as $course => $results) { ?>
<tr>
<th><?php echo $course; ?></th>
<?php foreach ($results as $score) { ?>
<th><?php echo $score; ?></th>
<?php } ?>
</tr>
<?php } ?>
</table>
Method 2: Fetch all rows in an array, so it becomes an array of arrays and use array_map with callback NULL to transpose it (See example 4 at http://php.net/manual/en/function.array-map.php).
You need to add the course names in the initial array to include them in the end result.
<table>
<tr>
<th>Subject</th>
<th>year1</th>
<th>year2</th>
<th>year3</th>
</tr>
<?php
$mysqli = new mysqli('localhost', 'user', 'pass', 'database');
$id = 1;
$data = array(array('HTML', 'CSS', 'Js'));
$query = $mysqli->query("SELECT HTML, CSS, Js FROM term WHERE Stdid='$id'");
while ($row = $query->fetch_assoc())
{
$data[] = $row;
}
$data = call_user_func_array('array_map', array_merge(array(NULL), $data));
?>
<?php
foreach ($data as $row): ?>
<tr>
<?php foreach ($row as $value): ?>
<th><?php echo $value?></th>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
Try this.
<table width = "1093" align="center" bgcolor="pink">
<tr align="center">
<td colspan="6"><h2>View Term</h2></td>
</tr>
<tr align="center" bgcolor="">
<th>S.N</th>
<th>Subject</th>
<th>Year 1</th>
<th>Year 2</th>
<th>Year 3</th>
</tr>
<?php
$db = mysqli_connect("localhost","root","YOURPASSWORD","YOURDATABASE");
if (mysqli_connect_errno())
{
echo"The Connection was not established" . mysqli_connect_error();
exit();
}
$get_term = "SELECT * FROM term WHERE Stdid='$id'";
$run_term = mysqli_query($db,$get_term);
$i =0 ;
while ($row=mysqli_fetch_array($run_term ))
{
// Get data from database.
// Change the input in $row[''] if the name of column is different in your tble "term".
$subject=$row['subject'];
$year1=$row['year1'];
$year2=$row['year2'];
$year3=$row['year3'];
$i++;
?>
<tr align="center">
<td> <?php echo $i;?></td>
<td><?php echo $subject;?></td>
<td><?php echo $year1;?></td>
<td><?php echo $year2;?></td>
<td><?php echo $year3;?></td>
</tr>
<?php }?>
</table>
Related
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
I want to store three variable values in an array. These are HomeResult, Draw and AwayResult. Which I want to use in an another php file. In the image u can se the final website. Problem is I can get the names of the teams and also the value of rows but result is not success.
Or is there another way to achieve this goal ?
I am not sure if it is the goed way to use B,E,F and O variable form the include php.
code of final site;
<table class="table">
<thead>
<tr>
<th>Home Team</th>
<th>Away Team</th>
<th>Result</th>
<th>B</th>
<th>E</th>
<th>F</th>
<th>O</th>
</tr>
</thead>
<tbody>
<?php
include 'ff.php';
include 'result.php';
foreach ($champs as $champ ) :
?>
<tr>
<td><?php echo $champ['HOME'];?></td>
<td><?php echo $champ['AWAY'];?></td>
<td></td>
<td><?php echo $champ['B'];?></td>
<td><?php echo $champ['E'];?></td>
<td><?php echo $champ['F'];?></td>
<td><?php echo $champ['O'];?></td>
</tr>
<?php
endforeach;
?>
file result.php
include 'champs.php';
$HomeWins=0;
$Draw=0;
$AwayWins=0;
foreach ($champs as $champ ) :
$B =$champ['B'];
$E=$champ['E'];
$F=$champ['F'];
$O=$champ['O'];
$sql = "SELECT * FROM England where B = '$B' AND E = '$E' AND F = '$F' AND O ='$O' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$rowcount=mysqli_num_rows($result);
// output data of each row
while($row = $result->fetch_assoc()) {
if($row['Q'] == 1){
$HomeWins++;
}
elseif($row['Q'] == 0){
$Draw++;
}else{
$AwayWins++;
}
}
$HomeResult =round(($HomeWins/$rowcount )*100);
$DrawResult = round(($Draw/$rowcount )*100);
$AwayResult =round( ($AwayWins/$rowcount )*100);
} else {
echo "0 results";
}
endforeach;
$conn->close();
?>
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>
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>
Here the value of $table will be passed from another file and it will be a table name in a database.
With that table name ($table) am trying to fetch its column names and all the values in the table and make the table look like an actual one we see in phpMyAdmin.
As a result of the code below. I can only get the column names. But not the data. Please tell me what should i do to perform the task of showing the datas in the table
<table cellpadding="0" cellspacing="0" border="0" width="100%" class="display" rel="datatable">
<thead>
<tr>
<?php
//echo"select * from $table";
$qq=mysql_query("show columns from $table");
if(mysql_num_rows($qq)>0){
//$i=1;
echo '<tr>';
while($rs = mysql_fetch_row($qq))
{
$sel=mysql_query("select * from $table");
$fetch=mysql_fetch_object($sel);
//while($fetch=mysql_fetch_object($sel))
//{
?>
<td><?php echo $fetch->$rs[0];?></td>
<?php
//}
//$i++;
}
echo '</tr>';
}
else
{
?>
<tr>
<td colspan="11">No data to display</td>
</tr>
<?php
}
?>
</tbody>
</table>
Yes only columns will be printing because you are printing $rs[0];?> where $rs holds object for mysql_query qq and it holds your column query only not
"select * from $table"
this.
Why dont you try displaying columns as a single row in html table and then try displaying data from other php set with seperate query structure .
Hope this way it helps.
I coudn't fix your code because it was getting ugly, so i remade it:
php:
function mysql_fetch_all($res) {
$result = array();
while ($row = mysql_fetch_row($res)) {
$result[] = $row;
}
return $result;
}
function getColumnsAndData($table) {
$table = mysql_real_escape_string($table);
$q1 = mysql_query("show columns from $table");
$q2 = mysql_query("select * from $table");
return array(mysql_fetch_all($q1), mysql_fetch_all($q2));
}
list($columns, $data) = getColumnsAndData($table);
?>
html
<table cellpadding="0" cellspacing="0" border="0" width="100%" class="display" rel="datatable">
<thead>
<tr>
<?php foreach ($columns as $column): ?>
<td><?php echo $column[0] . ' ' . $column[1] ?></td>
<?php endforeach; ?>
<tr>
</thead>
<tbody>
<?php if (count($data) > 0): ?>
<?php foreach ($data as $row): ?>
<tr>
<?php foreach ($row as $value): ?>
<td><?php echo $value ?></td>
<?php endforeach; ?>
<tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td>No data to display</td>
</tr>
<?php endif; ?>
</tbody>
</table>