I am trying to generate a table that takes data from a mysql database. There are 8 columns but the number of rows is variable depending on the amount of info from the database. The problem I'm running into is that I have two things that are variable and I don't know how to use two while loops (or if that's the right choice).
The code below can generate a table with 8 columns and a variable amount of rows but I don't know how to replace thing with sequential integers. I would like each cell to have just one integer in it sequentially like a while loop until the numbers = $end.
CODE:
<?php
$end=82; //will get all this data from a dabase
$rows=ceil($end/8);
$x=0;
$start=0;
?>
<table>
<?php
While ($x<=$rows){
echo"
<tr>
<td>
thing
</td>
<td>
thing
</td>
<td>
thing
</td>
<td>
thing
</td>
<td>
thing
</td>
<td>
thing
</td>
<td>
thing
</td>
<td>
thing
</td>
</tr>
";
$x++;
}
?>
</table>
This will output eight numbers per row starting at 1 and going to $end. I am unsure of what $maxprobs is here.
<?php
$end=82; //will get all this data from a dabase
$rows=ceil($end/8);
$x=0;
$start=0;
?>
<table>
<?php
while($x<=$rows) {
echo "<tr>";
for ($y = 0; $y < 8; $y++, $start++) {
if ($start <= $end) echo "<td>$start</td>";
}
echo "</tr>";
$x++;
}
?>
</table>
I have to ask - if you're pulling rows from a MySQL database, and you want your table to have a dynamic number of rows depending on the data, is there any specific reason you're not doing it the regular way, with a while loop and a mysql_fetch function?
$data = mysql_query("SELECT row1, row2, ... , row8 FROM table WHERE ...); // Sample query, edited for brevity.
echo "<table>";
while ($result = mysql_fetch_object($data))
(
echo "<tr>";
echo "<td>".$data->row1."</td>;
echo "<td>".$data->row2."</td>;
... // Edited for brevity. Include as many columns as you queried.
echo "<td>".$data->row8."</td>;
echo "</tr>";
}
echo "<table>";
Unless you have a really specific reason not to do it this way, I'd use this method. It's flexible and it will print as many rows as your query returns (meaning that you only need to change your query, not your code).
Additional information on mysql_fetch_object and mysql_query can be found here and here, respectively.
Take a look at the php website, nearly all their entries have examples, the database stuff shows a while loop, this is the best way to do it..
write the table opening tag, plus any headers..
while able to get more database data, get it, and do
display the table row open tag
display the row, by looping through the fields, and outputting them between cell tags
dispaly the end of row tag
now you've finished with your data, write the end of the table
There are a lot of examples about.
for the looping through the field, thats why they invented a "foreach" , eg wether you have 0, or 10000, you can go through each one, even if its not consecutive, so for each "fruit" in apple, pear, bannana..
Related
I have a database where teams will have multiple entries each with different locations. Each entry will have a team name. So for example, team1 might appear several times but each time the location will be different.
The structure of the DB is (each of these represents a column header):
team_name, first_name, last_name, location, arrival_time
My current working code creates HTML tables grouped by team name but currently only creates one row to show the first location and the time of arrival for the first location. I need this to dynamically create more rows to show all locations and arrival times for each team.
The desired result would look like this -
https://codepen.io/TheBigFolorn/pen/LqJeXr
But current result looks like this -
https://codepen.io/TheBigFolorn/pen/qgMppx
And here is an example of how the DB table might look -
https://codepen.io/TheBigFolorn/pen/daqJze
I've tried breaking up the echo and adding a second while loop before the row that I want to apply the above logic to but it seems to break everything. Any input on how I get this to work without having to use separate queries for each team would be very much appreciated. I'm new to php so please go easy on me :)
<?php
$leaders = "SELECT *, COUNT(location) FROM my_example_table GROUP BY team_name";
$result = mysqli_query($connect, $leaders) or die ("<br>** Error in database table <b>".mysqli_error($connect)."</b> **<br>$sql");
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "
<div class='red-border'>
<h2>". $row["team_name"]. "<br><small>Total locations visited: ". $row["COUNT(location)"]. "</small></h2>
</div>
<div class='data-holder'>
<table>
<tr>
<th>Location</th>
<th>Time of arrival</th>
</tr>
<tr><td>". $row["location"]. "</td> <td>". $row["arrival_time"]. "</td></tr>
</table>
</div>
";
}
} else {
echo "0 results";
}
?>
Your problem is due to the GROUP BY, as you've probably realised. This is necessary in order to get a count per team, but causes the number of rows output to be only 1 per team - that's what grouping does. Fundamentally, running an aggregate query such as a COUNT or SUM is incompatible with also outputting all of the row data at the same time. You either do one or the other.
Now, you could run two queries - one to get the counts, and one to get all the rows. But actually you don't really need to. If you just select all the rows, then the count-per-team is implicit in your data. Since you're going to need to loop through them all anyway to output them in the HTML, you might as well use that process to keep track of how many rows you've got per team as you go along, and create the "Total number of locations" headings in your HTML based on that.
Two things are key to this:
1) Making the query output the data in a useful order:
SELECT * FROM my_example_table Order By team_name, arrival_time;
2) Not immediately echoing HTML to the page as soon as you get to a table row. Instead, put HTML snippets into variables which you can populate at different times in the process (since you won't know the total locations per team until you've looped all the rows for that team), and then string them all together at a later point to get the final output:
$leaders = "SELECT * FROM my_example_table Order By team_name, arrival_time;";
$result = mysqli_query($connect, $leaders) or die ("<br>** Error in database table <b>".mysqli_error($connect)."</b> **<br>$sql");
$currentTeam = "";
$locationCount = 0;
$html = "";
$teamHtmlStart = "";
$teamHtmlEnd = "";
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
//run this bit if we've detected a new team
if ($currentTeam != $row["team_name"]) {
//finalise the previous team's html and append it to the main output
if ($currentTeam != "") $html .= $teamHtmlStart.$locationCount.$teamHtmlEnd."</table></div>";
//reset all the team-specific variables
$currentTeam = $row["team_name"];
$teamHtmlStart = "<div class='red-border'><h2>".$currentTeam."<br><small>Total locations visited: ";
$locationCount = 0;
$teamHtmlEnd = "</small></h2>
</div>
<div class='data-holder'>
<table>
<tr>
<th>Location</th>
<th>Time of arrival</th>
</tr>";
}
$teamHtmlEnd .= "<tr><td>". $row["location"]. "</td> <td>". $row["arrival_time"]. "</td></tr>";
$locationCount++;
}
//for the final team (since the loop won't go back to the start):
$html .= $teamHtmlStart.$locationCount.$teamHtmlEnd."</table></div>";
echo $html;
}
else {
echo "0 results";
}
Here's a runnable demo (using some static data in place of the SQL query): http://sandbox.onlinephpfunctions.com/code/2f52c1d7ec242f674eaca5619cc7b9325295c0d4
I have a webpage where it shows the lists of Projects and the monitoring of its progress/finances for every quarter. As shown below:
As you can see, my table is comprises of Project Name and a lists of sub-title's underneath it. And a series of columns per each quarter. Thru PHP I was able to populate the list of sub-titles under the Project Name, which also being fetched from the server side. Here's the code:
$sql = mysqli_query($con," My SELECT Statement ");
$i=0;
while($row = mysqli_fetch_assoc($sql)){
$ptitle = $row['Title'];
$iname = $row['Item'];
if($i%1)
{
?>
<?php } else { ?>
<tr>
<?php } ?>
<td width="25%"><?php echo $ptitle; ?></td>
<td></td>
</tr>
<tr>
<td><?php echo "<ul style='list-style-type: none;'><li>".nl2br($iname)."</li></ul>"; ?></td>
<td contenteditable="true" name="v1"></td>
Note: ptitle = ProjectName and iname = Semi-title underneath the Project's name.
Now, as you can see, the Project Name column literally "conquer" a single row on the left. Yet, the rows under the column of each quarter, should have its own separately, and must be parallel to the every sub-title underneath the Project Name. (Please refer to the image above for this) the only problem am encountering is... how can I make an editable row from inside a row, without affecting mysqli result? coz basically my table right now is kinda look like this:
Anyone who's more experience on this? I need your help.
PS: ...and oh! You might be wondering why do I include JSON in the title? It is because, I originally use JSON for editing those table rows before I even use mysqli_fetch_array. But when I include the results of the array inside the <table> tag, everything's changed and JSON is no longer working. So as of now, I am force to do it manually, meaning typing each <td contenteditable=true> in all of those rows. Yet, its not the desired output since I need another row within an existing row. Ideas? Anyone?
Figure Two:
Figure Three:
Count the number of lines in $iname, and then use a loop to create that many rows of contenteditable cells. You can also use this in the rowspan attribute of the <td> containing the title and subtitles.
$rows = substr_count($iname, "\n") + 1;
for ($i = 0; $i < $rows; $i++) {
echo "<tr>";
if ($i == 0) { ?>
<td rowspan='<?php echo $rows;?>' width='25%'><?php echo $ptitle . "<br>" . nl2br($iname);?></td>
<?php }
?>
<td contenteditable="true" name="v1"></td><td contenteditable="true" name="v2"></td>...
</tr>
<?php }
DEMO
I have to display time table (which store in the database-MySQL) in a web page using PHP. I can simply display it by using table. but one cell represent one hour.so for two hours lectures how can I merge 2 cells if adjacent cells include same subject? Please help me.
Further I should display those cells as text boxes and I should able to select those cells.
This is my code for display time table.
mysqli_select_db($connect,"timetable");
$result = mysqli_query($connect,"select * from 3yeariit2");
echo"<table border='1'>";
echo"<tr><th>Time</th>";
echo"<th>Monday</th>";
echo"<th>Tuesday</th>";
echo"<th>Wednesday</th>";
echo"<th>Thursday</th>";
echo"<th>Friday</th>";
echo"</tr>";
while($row = mysqli_fetch_array($result)){
$time = $row["time"];
$monday = $row["monday"];
$tuesday = $row["tuesday"];
$wednesday = $row["wednesday"];
$thursday = $row["thursday"];
$friday = $row["friday"];
echo"<tr><td>$time</td>";
echo"<td>$monday</td>";
echo"<td>$tuesday</td>";
echo"<td>$wednesday</td>";
echo"<td>$thursday</td>";
echo"<td>$friday</td>";
echo"</tr>";
}
echo"</table>";
For example among others, CST 391-2 [D1] should merge both 3.00-5.00 time slot in the image below
The method should be possible to apply in loading any other time table. Because I should display more time tables.
You can use the "colspan" or "rowspan" properties to merge rows or columns
It seems you just added time as single string in database and columns for days. Where as the better way is creating start time and end time as separate columns as per below.
subjectcode | subjectname | start | end | ...
Then you can easily add 2 hours subject using one row.
But in this case you can check next related subject and if the subject is same do the html row span. Thereafter in next iteration you need to skip adding <td> if particular subject was already printed using previous iteration.
I just explained the logic not the code. Hope it helps..
You can use "colspan" for merge more then one column and "rowspan" for merge more than one rows :
Like :
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td colspan="2"> </td>
<td rowspan="2"></td>
</tr>
</table>
I am at the end of my project, I have all the data from my database and everything is working fine I just can not work out how to display it in a table.
I have generated a table which is the (number of projects) * (the number of people).
The data I have collected is user_id, project_id and hours.
But how do I insert '6' (hours) into user_x's row in the column of the correct project?
I can only think to make x arrays (for the number of projects) of the length for the number of users and evaluate the project code to select the correct array and then use the user id to get the correct position to place the value and simply spit out the array into the td tag
This is incredibly messy, I wonder if I'm going about it completely wrong.
If this is indeed the best way I need to recursively create arrays and write code which references variables that might not even exist. Sounds insane to me
//for the length of projects create arrays that are the length of users and fill with 0's
for ($v = 0; $v < $rows_x; $v++){
$name = "variable{$v}";
$$name = array_fill(0, $rows_u, '0');
EDIT: What I am trying to do is show the number of hours that are booked to projects between two dates. I have gotten all the data correctly but now I need the data to land into a table so you can easily see which user booked to what project.
In an excel world I could use the project number to select the Y axis and the user id to select the X axis. However I don't know the best way to do this in php.
Surely creating an array for each project the length of the users and filling with data if there is data is not the best way.
I don't know if this is what you're looking for, but I insert my values into a table in the process of retrieving them.
You can echo the values into a <td> as long as they are in your SQL SELECT statement.
<table>
<thead>
<tr>
<th>Values1</th>
<th>Values2</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT value1, value2
FROM tbl_Values";
if (!$res = $link->query($sql)) {
trigger_error('Error in query ' . $link->error);
} else {
while ($row = $res->fetch_assoc()) {
?>
<tr>
<td>
<?php echo $row['value1']; ?>
</td>
<td>
<?php echo $row['value2']; ?>
</td>
</tr>
<?php
}
}
?>
</tbody>
</table>
This is the way I put data into my tables, without using arrays.
I have a while/for loop with thousands results. Since it contains several fields, I use table to display it. However, with thousands results being displayed at the same time, it will definitely slow down the performance. How can I display it in pagination?
<table>
<?php $count = 1000;
for($a=1;$a<=$count;$a++) { ?>
<tr>
<td><?php echo $a; ?></td>
<td>This is number <?php echo $a; ?></td>
</tr>
<?php $i++;
} ?>
</table>
My only solution without having a DB with the data would be to pass the array key you are on to the next page. For example:
$start = 1;
$end = 1000;
if(isset($_GET['record_number'])){
$start = $_GET['record_number'];
$end = $_GET['record_number'] + 1000;
}
for($a=$start; $a<=$end; $a++){
//code here
}
Other than that, you might consider creating a list of files in a DB engine so you can use the LIMIT parameter.
If the data comes from a database you can limit the result set. If you are using MySQL you use the LIMIT clause. This will allow you to only fetch the specified number of rows.
SELECT title, description FROM posts LIMIT 25
This will only fetch 25 rows. Then if you want to fetch the results after row 25 you can provide an offset. This is done a little different since the offset comes first in the LIMIT clause. Only one argument is provided MySQL assumes its the limit instead. To select the next 50 rows you use.
SELECT title, description FROM posts LIMIT 25, 50
This can be useful to reduce the result set fetched and help increase performance/load times due to a smaller amount of data that needs to be processed.
I hope this can help you, happy coding!
Update
This is a little tutorial in using the LIMIT clause in MySQL
Here is my example, it's similar to the answer from #AnotherGuy
<form method="GET">
<input type="text" name="rowsPerPage">
<?php
for($i = 1; $i+1 < $count/$rowsPerPage; $i++){
echo '<input type="submit" name="page" value="'.$i.'">';
}
?>
</form>
<?php
$begin = (int)$_GET['rowsPerPage']*$_GET['page'];
$take = (int)$_GET['rowsPerPage'];
$sql = "SELECT ... LIMIT {$begin}, {$take}";
?>
It's possible that the code contains "typos", but I hope it will give you new ideas.
I would recommend you to use GET instead of POST. GET will be saved in the URL, in this way, it will be easier to reload the page without losing the page-settings.
www.example.com?rowsPerPage=150&page=2