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
Related
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>
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>
I'm just learing to use php, and I've been working on this code that is not very efficient because it is very long and I would like it to be more automated. The idea is to generate a table with 2 colums, one with the user name and the other with the score of each user. As you may imagine, the score is based on a function that use other variables of the same user. My goal is to only have to set one variable for each user and a new row is would be created automatically at the end of the table.
<?php
$array1['AAA'] = "aaa"; ## I'm suposed to only set the values for array1, the rest
$array1['BBB'] = "bbb"; ## should be automatic
$array1['ETC'] = "etc";
function getscore($array1){
## some code
return $score;
};
$score['AAA'] = getscore($array1['AAA']);
$score['BBB'] = getscore($array1['BBB']);
$score['ETC'] = getscore($array1['ETC']);
?>
<-- Here comes the HTML table --->
<html>
<body>
<table>
<thead>
<tr>
<th>User</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr>
<td>AAA</td> <-- user name should be set automaticlly too -->
<td><?php echo $score['AAA'] ?></td>
</tr>
<tr>
<td>BBB</td>
<td><?php echo $score['BBB'] ?></td>
</tr>
<tr>
<td>ETC</td>
<td><?php echo $winrate['ETC'] ?></td>
</tr>
</tbody>
</table>
</body>
</html>
Any help would be welcome!
$outputHtml = ''
foreach( $array1 as $key => $val )
{
$outputHtml .= "<tr> ";
$outputHtml .= " <td>$key</td>";
$outputHtml .= " <td>".getscore($array1[$key]);."</td>";
$outputHtml .= " </tr>";
}
then in $outputHtml will be html content with all rows you wanna display
This is a little cleaner, using foreach and printf:
<?php
$array1 = array(
['AAA'] => "aaa",
['BBB'] => "bbb",
['ETC'] => "etc"
);
function getscore($foo) {
## some code
$score = rand(1,100); // for example
return $score;
};
foreach ($array1 as $key => $value) {
$score[$key] = getscore($array1[$key]);
}
$fmt='<tr>
<td>%s</td>
<td>%s</td>
</tr>';
?>
<-- Here comes the HTML table --->
<html>
<body>
<table><thead>
<tr>
<th>User</th>
<th>Score</th>
</tr></thead><tbody><?php
foreach ($array1 as $key => $value) {
printf($fmt, $key, $score[$key]);
}
?>
</tbody></table>
</body>
</html>
Also, I'll just note that you don't seem to be using the values of $array1 anywhere. Also,
I'm not sure what $winrate is in your code, so I ignored it.
I've created a PHP program for adding and viewing reminders. The add page works, but I'm having some trouble displaying them properly. How should I code this to only get the actual data? Also, how could I put this into an HTML table? (i.e. column for name, description, and date; rows are the retrieved data)
Thanks
When I open the file in my browser I get this as an output:
Array ( [reminderID] => 14 [reminderName] => Test [reminderDescript] => Test_Descript [reminderDate] => 2012 05 7 )
Code:
<?php include 'header.php'; ?>
<?php include 'database.php'; ?>
<div id="content">
<h1>Reminder List</h1>
<table align ="center">
<thead>
<tr>
<td>Name</td>
<td>Description</td>
<td>Date</td>
</tr>
</thead>
<?php
$query = 'SELECT * FROM reminder_event';
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
print_r($row);
}
?>
</table>
<p><a href='reminder_add.php'>Add Reminder</a></p>
</div>
<?php include 'footer.php'; ?>
print_r() is a diagnostic tool for debugging, not to be used for real output. Instead, output HTML to a table using the array keys fetched from your row.
// Open a table
echo "<table>";
while($row = mysql_fetch_assoc($result)) {
// Output each row
echo "<tr>
<td>{$row['reminderName']}</td>
<td>{$row['reminderDescript']}</td>
<td>{$row['reminderDate']}</td>
</tr>";
}
// Close the table
echo "</table>";
Better still, escape each of the values for HTML output with [htmlspecialchars()] (http://us3.php.net/manual/en/function.htmlspecialchars.php) before output to prevent cross-site scripting attacks and broken HTML if characters like < > & are encountered in the values.
echo "<table>";
while($row = mysql_fetch_assoc($result)) {
// Encode all values for HTML output
$name = htmlspecialchars($row['reminderName']);
$desc = htmlspecialchars($row['reminderDescript']);
$date = htmlspecialchars($row['reminderDate']);
// Then output the encoded values
echo "<tr><td>$name</td><td>$desc</td><td>$date</td></tr>";
}
echo "</table>";
Change:
while($row = mysql_fetch_assoc($result)) {
print_r($row);
}
To:
while($row = mysql_fetch_assoc($result)) {
echo $row['reminderID'];
echo $row['reminderName'];
echo $row['reminderDescript'];
echo $row['reminderDate'];
}
You can echo those values out in whatever HTML you'd like. So, for example, if you want it in a table you would do something like this:
echo "<table><tr>";
while($row = mysql_fetch_assoc($result)) {
echo "<td>" . $row['reminderID'] . "</td>";
echo "<td>" . $row['reminderName'] . "</td>";
echo "<td>" . $row['reminderDescript'] . "</td>";
echo "<td>" . $row['reminderDate'] . "</td>";
}
echo "</tr></table>";
You can clean that up a bit to take some (or all) of the HTML out of the PHP.
<?php include 'header.php'; ?>
<?php include 'database.php'; ?>
<div id="content">
<h1>Reminder List</h1>
<table>
<thead><tr><td>id</td><td>name</td><td>description</td><td>date</td></tr></thead>
<tbody>
<?php
$query = 'SELECT * FROM reminder_event';
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) { ?>
<tr>
<td><?php echo $row['reminderID']; ?></td>
<td><?php echo $row['reminderName']; ?></td>
<td><?php echo $row['reminderDescript']; ?></td>
<td><?php echo $row['reminderDate']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<p><a href='reminder_add.php'>Add Reminder</a></p>
</div>
<?php include 'footer.php'; ?>
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>