I am using a for loop to generate a table for a SQL query's results. I am trying to alter the code so that new text is echoed into a specific column of the table (column 8)
$fields_num = mysql_num_fields($result);
echo "<h1>Table: {$table}</h1>";
echo "<table border='0' id=resultTable><tr>";
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td id" . $i;
echo "></td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
?>
what actually do you mean by "new text" in "I am trying to alter the code so that new text is echoed into a specific column of the table"?
Is "text" the name of a particular table field? If so, it would be better to alter the sequence of the fields in the mysql_query that you are using instead of doing any change in the html generation for this
e.g.
SELECT field1, field2, ... new_text from ...
Put new_text in the eighth position.
Update
If you want to display various things for various columns in the result table, you can put a counter and do what you want as per count like this:-
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
$counter = 0;
foreach($row as $cell)
{
if($counter == 7)
{//eighth column
echo "<td><img src='".$cell."' /></td>";
}
else if($counter == 5)
{//sixth col
echo //something else ...
}
else
echo "<td>$cell</td>";
//inside your default td
$counter++;
}
echo "</tr>\n";
}
But it would be more readable,maintainable and customizable to have some config array where you specify which column is going to hold what like this:-
function getColumnConfigs()
{
return $columnsConfigs = array(5=> "something_else", 7 => "img");
//specify special cases for necessary columns. columns not mentioned here will take default.
}
and then use this in your iteration:-
// printing table rows
$columnsConfig = getColumnConfigs();
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
$counter = 0;
foreach($row as $cell)
{
if(isset($columnsConfig[$counter]))
{
switch($columnsConfig[$counter])
{
case "img":
$html = "<td><img src='".$cell."' /></td>";
break;
case "something_else"
$html = "<td><img src='".$cell."' /></td>";
break;
}
}
else
{//default
$html = echo "<td>$cell</td>";
}
}
echo "</tr>\n";
}
Related
I want to create a game where I have to create a map with PHP. I want to create 100 tables boxes in the right way but I can't get it work...
$field = 100;
echo "<table border='3px' dir='ltr'>";
for ($row=0; $row < 10 ; $row++) {
echo "<tr>";
for ($column=0; $column < 10; $column++) {
echo "<td>";
echo $field;
$field--;
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
This gives me this table:
But I will need a table like:
If a for loop is not a requirement.
I would use an array, then you have a set to work from rather then calculating things, then you just need reverse the odd row, like so:
$rows = array_reverse(array_chunk(range(1, 100), 10));
echo "<table>\n";
foreach ($rows as $level => $row) {
if (($level-1) % 2) {
$row = array_reverse($row);
}
echo "\t<tr>\n";
foreach ($row as $value) {
echo "\t\t<td>$value</td>\n";
}
echo "\t</tr>\n";
}
echo "<table>\n";
https://3v4l.org/204eh
I am working on a project to pull data from a sql database via PHP and create an HTML table from it. It is part of a form I am creating and the table will be a listing of what I am selling, costs, weights, etc. Anyway, I need to do this with PHP. So far I have the following in this section of my code to make this table:
<?php
$db=mysqli_connect(null,null,null,'weblab')
or die("Can't connect to DB: " .
mysqli_connect_error());
$query="SELECT fruit_item_no, fruit_name, fruit_price, fruit_weight FROM fruit_$
$result=mysqli_query($db, $query);
if (!$result) {
print "Error - The query could not be executed!" .
mysqli_error();
}
print "<table class = 'main'><caption> <h2> Fruit Purchasing Form </h2> </c$
print "<tr align = 'center'>";
$num_rows=mysqli_num_rows($result);
if ($num_rows > 0) {
$row=mysqli_fetch_assoc($result);
$num_fields=mysqli_num_fields($result);
$keys=array_keys($row);
for ($index = 0; $index < $num_fields; $index++)
print "<th class='a'>" . $keys[$index] . "</th>";
print "</tr>";
for ($row_num = 0; $row_num < $num_rows; $row_num++) {
print "<tr>";
$values = array_values($row);
for ($index = 0; $index < $num_fields; $row_num++) {
$value=htmlspecialchars($values[$index]);
print "<td class = 'b'>" . $value . "</td>";
}
print "</tr>";
$row=mysqli_fetch_assoc($result);
}
}
else {
print "There were no such rows in the table <br />";
}
print "</table>";
?>
The problem I am running into is when I attempt the view the entire page in Chrome, all I see is:
I think the error is somewhere around this section of code:
for ($row_num = 0; $row_num < $num_rows; $row_num++) {
print "<tr>";
$values = array_values($row);
for ($index = 0; $index < $num_fields; $row_num++) {
$value=htmlspecialchars($values[$index]);
print "<td class = 'b'>" . $value . "</td>";
If anyone can give me a little direction on what I might be missing, I would greatly appreciate it. I have been researching a while now and no clear fix has come up that i can see.
UPDATE:
Thought it would be best to just update my post instead of new question or comment somewhere. Thanks to all your suggestions I was able to correct my code to properly display my table and worked out all validation errors. I apologize for the code reading nightmare... I am still fairly new at this and I need to work more at it.
I did run into one issue I still cannot resolve though. I am trying to add an input box on the end of each row in the table I created. Problem is no matter what I try the boxes stay in a line above the table (pretty much at the top of the browser screen.
I placed this line in the sql query block to try to get the input box:
echo ("<input name='item[]' type='text' .=''/>");
and I also tried:
echo ("<input type='text' name ='item'/>");
Both did the same thing in giving me the line of boxes along the top. Any direction you could provide in getting these to be at the end of each row? I do not need it to put data back in the database or add to a table there. I just am trying to get input fields that will allow input that will submit with my form.
You can simplify the code by running and while loop on the result and iterating through the rows. And then using foreach loops since each row is an array of key value pairs. On the first iteration you could print the header.
$num_rows=mysqli_num_rows($result);
if ($num_rows > 0) {
$i = 0;
// loop through each row in the result
while ($row=mysqli_fetch_assoc($result)) {
// if first then print the header
if ($i == 0) {
print "<tr>";
foreach ($row as $field => $value) {
print "<th class='a'>".$field."</th>";
}
print "</tr>";
}
// print the row
print "<tr>";
foreach ($row as $value) {
print "<td class='b'>".$value."</td>";
}
print "</tr>";
$i++;
}
}
else {
print "<tr></td>There were no such rows in the table</td></tr>";
}
As suggested in the comments it would be a good idea to separate your view from your code.
In your second for loop, you have this:
for($index=0; $index<$num_fields; $row_num++)
Well, the value of $index will remain 0 throughput your execution. Try changing it to
for($index=0; $index<$num_fields; $index++)
{
$row_num++;
//rest of code
}
Hope it helps.
This is unnecessarily complicated:
$row=mysqli_fetch_assoc($result);
$num_fields=mysqli_num_fields($result);
$keys=array_keys($row);
for ($index = 0; $index < $num_fields; $index++)
print "<th class='a'>" . $keys[$index] . "</th>";
print "</tr>";
for ($row_num = 0; $row_num < $num_rows; $row_num++) {
print "<tr>";
$values = array_values($row);
for ($index = 0; $index < $num_fields; $row_num++) {
$value=htmlspecialchars($values[$index]);
print "<td class = 'b'>" . $value . "</td>";
}
print "</tr>";
$row=mysqli_fetch_assoc($result);
}
Something like this would be easier to read and should solve your problem, which was caused by incrementing the wrong index on one of the for loops:
$headers = false;
while($row=mysqli_fetch_assoc($result)) {
if (!$headers) {
echo "<thead><tr>";
foreach($row as $k=>$v) {
echo "<th>$k</th>";
}
echo "</tr></thead>";
$headers = true;
}
echo "<tr>";
foreach ($row as $k=>$v) {
$v=htmlspecialchars($v);
print "<td class='b'>$v</td>";
}
echo "</tr>";
}
But I would strongly recommend a) using a database abstraction layer like PDO, and b) separating your logic from your presentation. Debugging problems with HTML is made 100 times harder when it's jumbled all together with your PHP like this.
I am stuck in a weird problem, I want to show the continuous number till the last in the row and cols,
instead of that its showing form 1-50 and then again the row starts with 1 up-to 50.
<?php
$rows = 10;
$cols = 50;
$x=1 ;
echo "<table border='1'>";
for($tr=1;$tr<=$rows;$tr++){
echo "<tr>";
for($td=1;$td<=$cols;$td++){
echo "<td>$td</td>";
}
echo "</tr>";
}
echo "</table>";
?>
Thanks
$rows = 10;
$cols = 50;
$x=1 ;
echo "<table border='1'>";
for($tr=1;$tr<=$rows;$tr++){
$style = "green";
if ($tr % 2 == 0) {
$style = "#ccc";
}
echo "<tr style='background-color:".$style."'>";
for($td=1;$td<=$cols;$td++)
{
echo "<td>$x</td>";
$x++;
}
echo "</tr>";
}
echo "</table>";
You are outputting $td which resets at every new tablerow.
Instead, you would like to output an incrementing $x, if I'm not mistaken.
<?php
$rows = 10;
$cols = 50;
$x=1 ;
echo "<table border='1'>";
for($tr=1;$tr<=$rows;$tr++){
echo "<tr>";
for($td=1;$td<=$cols;$td++){
echo "<td>" . $x . "</td>";
$x++;
}
echo "</tr>";
}
echo "</table>";
?>
In response to your comment on another answer: if you would want alternating row colors, you could use $tr and check wether it is even or uneven:
if($tr % 2 == 0)
{
// use color1
}
else
{
// use color2
}
I'm trying to display all the information in a msSQL table in an HTML table and have up with something that is not so great.
<table border="1">
<?
echo "<tr>";
for ($i = 0; $i < mssql_num_fields($result); ++$i){
echo "<th>" .$column_names[$i] . "</th>";
}
echo "</tr>";
$num_rows = mssql_num_rows($result);
for ($i = 0; $i < $num_rows; ++$i){
echo "<tr>";
foreach ($column_names as $key => $val){
$result_row = mssql_query("SELECT * FROM username WHERE id = '$i'");
$row = mssql_fetch_assoc($result_row);
echo "<td>";
echo $row[$val];
echo "</td>";
}
echo "</td>";
}
?>
</table>
This works. The first part prints out the column names successfully, but as for the rest:
1) I think it is sort of cumbersome to make a query for every time through the loop
2) it doesn't really work because the ids of the rows go much higher than the number of rows in the table, as some ids aren't used.
It seems like I should be able just make one query and pull everything from the database at one go, then build my HTML table from that, but I can't figure out how to access it row by row where I could go $row[next row][shifted value from $column_names. How can improve this query?
function table_cell($item, $header=false) {
if (!$item) return '';
$elemname = ($header) ? 'th' : 'td';
$escitem = htmlspecialchars($item, ENT_NOQUOTES, 'UTF-8');
return "<{$elemname}>{$escitem}</{$elemname}>";
}
function table_header_cell($item) {
return table_cell($item, true);
}
function table_row($items, $header=false) {
$func = ($header) ? 'table_header_cell' : 'table_cell';
return "<tr>\n\t".implode("\n\t", array_map($func, $items))."\n</tr>\n";
}
function echo_result_as_table($result) {
if ($result && $row = mssql_fetch_assoc($result)) {
$columnnames = array_keys($row);
echo "<table>\n", table_row($columnnames, true), "\n";
do {
echo table_row($row), "\n";
} while ($row = mssql_fetch_assoc($result));
echo "</table>\n";
}
}
$result = mssql_query("SELECT * FROM username");
echo_result_as_table($result);
if ($result) mssql_free_result($result);
If you have an array of associative arrays instead of a raw mssql result handle, you can use a function like this to produce a table string:
function array_to_table($arrayofassoc) {
if (!$arrayofassoc) return '';
$tablestr = '<table>';
$tablestr .= table_row(array_keys($arrayofassoc[0]), true);
$tablestr .= implode('', array_map('table_row', $arrayofassoc));
$tablestr .= '</table>';
return $tablestr;
}
try this:
while($row = mysql_fetch_results($result)){
echo '<td>'.$row['column_name'].'</td>';
}
with 'column_name' being the name of the column in mysql.
but some will say..."wait, but PDO"
I am looking to add column IDs to a table created by a foreach loop like this. Help is appreciated!:
echo "<h1>Table: {$table}</h1>";
echo "<table border='0'><tr>";
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
Thanks,
Mike
I quite don't understand if you need an id for each cell or row or... column ?
For row :
$i = 1;
while($row = mysql_fetch_row($result))
{
echo '<tr id="row-"'.$i.'">';
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
$i++;
}
For cell :
$i = 1;
while($row = mysql_fetch_row($result))
{
echo '<tr>';
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo '<td id="cell-"'.$i.'">$cell</td>';
echo "</tr>\n";
$i++;
}
Notes :
1-
Why are you using this :
echo "<table border='0'><tr>";
echo "</tr>\n";
instead of :
echo "<table border='0'><tr></tr>\n";
or even better :
echo "<table border='0'><tr><td></td></tr>";
Since you know you're using only one cell.
2-
Since you're introducing a int as an id (well, it's usually the case... incremental Ids) and that html's id can't start with a number, you must put something in front of it.
while($row = mysql_fetch_assoc($result)){
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $colName=>$colValue)
// do wathever you like here
echo "</tr>\n";
Regards
#user547794: I'm not entirely sure what you mean, but if you just wish to assign an id to each cell, this should do the trick --
echo "<h1>Table: {$table}</h1>\n";
echo '<table cellspacing="0">' . "\n";
$i = 1;
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>\n";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
{
echo '<td id="r' . $i . '">$cell</td>' . "\n";
}
echo "</tr>\n";
$i++;
}
echo "</table>\n";