I am creating a table and want it laid out a certain way and have to retrieve the data from the DB. I am trying to get it set up where it has the usernames across the top example...
Jim Chris Allen Rick
7 8 4 5
my code looks like this and I have been messing around with it for hours and cant figure out why I cant get it set up how I want. Any help would be appreciated. Its a while loop.
while ($pickresults= mysql_fetch_assoc($picksquery)) {
//first row
echo '<th> '.$pickresults['username'].' </th> ';
echo ' <td> '.$pickresults['firstgame'].' </td> '; }
First off, you should learn the HTML code for tables. Your code is putting a Table Header (th) next to a normal column item (td). You need to loop through the headers first then next row loop through the column items or build the strings to echo out.
$headers = $col = "";
while($pickresults= mysql_fetch_assoc($picksquery)){
$headers .= "<th> {$pickresults['username']} </th>";
$col .= "<td> {$pickresults['firstgame']} </td>";
}
echo "<table><tr>$headers</tr><tr>$col</tr></table>";
Your structure is creating a TH then a TD and then a TH and then a TD etc.
This isn't how you create a table, you first need to make the four TH's and THEN you can make the four TD's.
Edit: Marko D has supplied the code to explain what I mean.
First collect table header and body, and then output them. The way you were doing, html was like this, I guess it's easy to see what is wrong with html
<th>name</th>
<td>value></td>
<th>another name</th>
<td>another value</td>
What you need is this:
$td = '';
$th = '';
while ($pickresults= mysql_fetch_assoc($picksquery)) {
$th .= '<th> '.$pickresults['username'].' </th> ';
$td .= '<td> '.$pickresults['firstgame'].' </td> ';
}
echo '<table><tr>' . $th . '</tr><tr>' . $td . '</tr>' . '</table>';
You need to write all usernames in <th>-tags.
I'd put it in an array first, and from the array into the table...
while ($pickresults= mysql_fetch_assoc($picksquery)) {
$picked[]=$pickresults;
}
echo "<table><tr>"; // create table and 1st row
foreach ($picked as $pick) {
echo "<th>{$pick['username']}</th>"; // create 1st line headers
}
echo "</tr><tr>"; // close 1st row and open 2nd
foreach ($picked as $pick) {
echo "<td>{$pick['firstgame']}</td>"; // create 2nd line...
}
echo "</tr></table>"; // close 2nd row and table
Related
Help me, i got stack when i want to make a dynamic table,
so the idea of the program is we can be costume a select field of database and can show it.
so if we have this field on table in database :
No
Name
age
Address
and we just want to show Name and Address, so i save the rule on the database (SELECT Name, Address)
but the problem is on the dynamic table when i show, how to make dynamic table when field always change (Example :Maybe the field just Age, or Name and age or we show all #its just from Configure that i make)
i have tried to make query result into an array and show it like this.
<table>
<?php for($x=0;$x<$length_array;$x++){ ?>
<tr>
<?php for($y=0;$y<$width_array;$y++){ ?>
<td><?php $result[$length_array][$width_array] ?></td>
<?php } ?>
</tr>
<?php } ?>
</table>
note : variable $result is from result query and i change it into an array, but the problem is i cann't count a length and width from array in this code.
It depends a bit on how your result set is returned, but based on your code above I'll assume your result is an array of arrays.
First think about what you want: you want an html table with a header that gives the name for each column, and then has a row for each record in your result set.
I very much dislike mixing php and html, so I will use a different syntax style, but the steps are the same no matter what style you use. This way makes the logic a lot easer to read.
First, make the table.
<?php
$html = '<table>';
Now you want to add a header to the table and create a cell for each column in your result. Before you do that, you need to answer: where are you going to get the names for you columns? There are two possible answers; 1) directly from the results of your query, or 2) hard-code them.
Getting them directly from the query results is much more flexible, but the names you give your database columns may not always be human-friendly.
$columnNames = ['Name', 'Address'];
---- OR ----
$firstRow = $result[0]; // of course we have checked that the result set is not empty!
$columnNames = array_keys($firstRow); // adjust if rows are objects instead of arrays
Now output the header:
$html .= '<thead>';
foreach($columnNames as $columnName) {
$html .= '<th>' . $columnName . '</th>';
}
$html .= '</thead>';
Now we can move on to the body, as in the answer to your previous question, creating a row in the table for each item in your result set. For each row you have an inner loop that creates the markup for each cell.
$html .= '<tbody>';
foreach($result as $row) {
$html .= '<tr>';
foreach($row as $cell) {
$html .= '<td>' . $cell . '</td>';
}
$html .= '</tr>';
}
$html .= '</tbody>';
$html .= '</table>';
print $html;
The forum pages on my website use PHP to create a table and then use a while loop to populate it from the database. This works fine and always has but I have tried to move the anchor, 'link', tag from around the post's title to the entire first section of the post within the table. To do this it goes through the following steps:
Open the table tag [OUTSIDE OF LOOP]
Echo headers [OUTSIDE OF LOOP]
Start WHILE loop that makes another post section for every post found.
Create table row
Create table data
Echo content
Close table data
REPEAT STEPS 5-7 ONCE MORE for post date section
Close table row
close table [OUSTIDE OF LOOP]
It should make the links clickable on all of the first section and they should be within the table like this:
<table> <--- *THIS IS BEFORE THE LOOP, IT GETS RUN ONCE ONLY* -->
<WHILE *do this like 5 times or something*>
<tr>
<a *category link*>
<td>
*content for the 'td' which is taken from the DB*
</td>
<td>
*content for the 'td' which is taken from the DB*
</td>
</a>
</tr>
<ENDWHILE>
</table>
However, in practice they end up outside of the table as can be seen in this screenshot:
Could anyone please explain this and how to fix it?
echo '<table class="forumTable">
<tr>
<th>Category</th>
<th>Last topic</th>
</tr>';
while($row = mysqli_fetch_assoc($catResult)){
echo '<tr>';
echo '<a href="category.php?id=' . htmlspecialchars($row['catID']) . '"><td class="catDesc">';
echo '<h3>' . $row['catName'] . '</h3>' . $row['catDesc'];
echo '</td>';
echo '<td class="catTime">';
$getTops = "SELECT topicID, topicSubject, topicDate, topicCat FROM topics WHERE topicCat = " . $row['catID'] . " ORDER BY topicDate DESC LIMIT 1";
$topResult = mysqli_query($connect, $getTops);
if(!$topResult){
echo '<p style="margin-top: 75px;">The last topic could not be displayed, please try again later.</p>';
}
else{
if(mysqli_num_rows($topResult) == 0){
echo '<p>No topics</p>';
}
else{
while($topRow = mysqli_fetch_assoc($topResult)){
echo '' . $topRow['topicSubject'] . ' at ' . $topRow['topicDate'];
}
}
}
echo '</td></a>';
echo '</tr>';
}
echo '</table>';
Since the source page confirms that the anchors are where you placed them, but the browser moves them around, you can either :
- contain your links inside the td table cell
- use an alternative approach to add the link where you want it html - table row like a link
Did you try to get page not from browser? How it looks?
I think browser does not allow you to put <a> into <table> directly without <tr><td> </td></tr>
I have following PHP code contain 2 foreachs
echo "<table class='table table-bordered'>";
foreach($resultOld as $key=>$value)
{
foreach ($value as $key1 => $subjects) {
$checked = $subjects;
echo "<tr><tr class=\"".$subjects."\">$key1
<input type='checkbox' class=\"".$subjects."\" value='checked' name=\"".$key1."JAN\" $checked/> </tr>
</tr>" ;
}
}
echo "</table>";
$resultOld is a fetchAll(PDO::FETCH_ASSOC) output and it contains a two dimensional array. $subjects will return 661 words from the database which means the $resultOld array have 661 elements. And after every 12 cells I want to start a new line (tr). That means I need 55 rows in the table. How to achieve this using PHP?
If you want a new row after every 12 records, you need to use a counter and check the count -
$counter = 1;
echo "<table class='table table-bordered'>";
echo "<tr>"; //start the first row
foreach($resultOld as $key=>$value)
{
foreach ($value as $key1 => $subjects) {
// if the 13th cell, end last row, and start new row
if ($counter%12==1){
echo "</tr><tr>";}
$checked = $subjects;
echo "<td class=\"".$subjects."\">$key1
<input type='checkbox' class=\"".$subjects."\" value='checked' name=\"".$key1."JAN\" $checked/> </td>" ;
// increase counter
$counter++;
}
}
echo "</tr>"; // end last row
echo "</table>";
First, note that your HTML structure is wrong. I recommend thinking about this is a little more steps. Perhaps layout a single row <table> HTML structure for reference between slicing it up into PHP
Here's an example:
<table class="...">
<tbody> <!-- I recommend using the tbody tag -->
<tr>
<td>...</td>
</tr>
</tbody>
</table>
There's three basic things to think about:
The Table Body
The Row
The Columns (ie. Cells)
Step 1 is to print the table body. You're doing fine here:
echo '<table class="table table-bordered">';
echo '<tbody>';
//...
<echo '</tbody>';
echo '</table>';
Step 2 is to loop through your rows
echo '<table class="table table-bordered">';
echo '<tbody>';
// Loop Through Rows
foreach($resultOld as $key=>$value)
{
echo '<tr>'; // start a new row
// ...
echo '</tr>'; // end a row
}
<echo '</tbody>';
echo '</table>';
Step 3 is to loop through each column or cell of the table:
// STEP 1
echo '<table class="table table-bordered">';
echo '<tbody>';
// STEP 2
// Loop Through Rows
foreach($resultOld as $key=>$value)
{
echo '<tr>'; // start a new row
// STEP 3
foreach ($value as $key1 => $subjects) {
$checked = $subjects;
// Start a new column/cell
echo '<td class="' . $subjects . '">';
// Print cell contents
echo $key1;
echo '<input type="checkbox" class="' . $subjects . '" value="checked" name="' . $key1 . 'JAN" '. $checked . '/>';
// End column/cell
echo '</td>';
} // END STEP 3
echo '</tr>'; // end a row
} // END STEP 2
echo '</tbody>';
echo '</table>';
// END STEP 1
Some notes on your code:
You're printing 2 Table rows instead of printing a table row and a table column (ie: <tr><tr> instead of <tr><td>;
You need to print the row inside the first loop, not the second loop.
The second, nested, loop prints out your 2nd dimension or columns.
For me, I like to use single quotes (') with printing HTML. I do this because I use double quotes (") for HTML attributes. This allows me to avoid having to escape the double quote character and getting a hard to read '\""' situation, which can cause simple syntax bugs.
Also when running into problems printing HTML, braking the HTML into multiple echo/print statements can help you structure your code and troubleshoot the problems. Once it's working you can go back and refactor them into a single echo statement, however the performance difference would probably so minor that it's not worth the time.
I hope that helps!
I'm stuck and can't figure this out.
I have this piece of code which is basically generating a table taking data from SQL cursor.
I need to add one extra table row <tr> (which will be filled with additional info) after each row. I've tried putting the new row in several places, but there is never any output data for it. This is someone else's code that I'm trying to modify.
$top_i=min($pagesize-1,$numrows-$start);
for($i = 0;$i<=$top_i;$i++) {
if (($i%2)==1)
echo "<tr class='saraksts_row0'>";
else
echo "<tr class='saraksts_row1'>";
$res=mssql_query("fetch absolute ".($start+$i)." from saraksts_cursor ");
$row=mssql_fetch_array($res);
$itemp = 0;
foreach($fields as $field) {
$key = $field[0];
if($field[2]) {
eval($field[2] );
}
$itemp++;
$val = ($row[$key] == "") ? " " : $row[$key];
// Get rid of right and left border, set topmost border
$st="";
if ($itemp==1)
$st.="border-left-style:none;";
if ($itemp==$numfields)
$st.="border-right-style:none;";
if ($i==$top_i)
$st.="border-bottom-style:solid;";
echo "<td style='$st'>$val</td>";
}
$itemp = 0;
echo "</tr>\n";
}
The place where you want to add the extra row is after closing the first row and before the iteration moves to the next one. Note, it appears that you are doing some styling based on whether the row is odd or even. If you want this new row to have the same styling, I suggest you store the class you're applying to the preceding row so that you can also apply it to this row.
echo "</tr>\n";
echo "<tr><td>...</td><td>...</td></tr>\n"; /* Add the new row here */
}
...
$st.="border-bottom-style:solid;";
echo "<td style='$st'>$val</td>";
}
//Here we go
echo '<td style="blah">'.$yourotherinfo.'</td>';
$itemp = 0;
echo "</tr>\n";
Running a mysql query that returns users with their daily highscores.
This is the php file that displays the highscore:
<table border="0" width="100%"><?php echo highscore()?>
</table>
This is the php that handles the mysql query (highscore function):
echo '<tr>';
echo '<td>'.$user.'</td><td align="right">'.$score.'</td>';
echo '</tr>';
The mysql query that I have results in the user with the highest score getting on top of the table that you see above.
Now I would like to add a crown to the user that has the most points.
The question is how to add an image(crown.png) to the first row which is the user with the highest score.
Thanks in advance.
I assume you order users by score DESC.
$set = 0;
while() {
echo '<tr';
echo '<td>';
if(!$set) {
echo '<img src="crown.png" alt="crown" />';
}
// ... the rest of the code
$set = 1;
}
if (empty($notfirst)){
echo "crown";
$notfirst=1;
}
i only see a quick and dirty solution, given the code you provide.
I guess you call this code in a loop?
echo '<tr>';
echo '<td>'.$user.'</td><td align="right">'.$score.'</td>';
echo '</tr>';
so just declare a variable before you start the loop:
$first = true;
then inside your loop, change your code to:
echo '<tr>';
echo '<td>'.$user.'</td><td align="right">'.$score.'</td><td>'.$first?'<img src=\"crown.png\" />':''.'</td>';
echo '</tr>';
$first = false;
If you wanted to do this sans PHP you could make your table and use CSS3's new :first-child pseudo-selector to add the crown as a background image to the first row.
table tr:first-child { background: url("crown.gif") no-repeat; }