Hello I am trying to solve a problem. I've research and take time but unable to solve it sorry for that.
I am trying to show a database table query result in multiple table on a html page and every table should be a range i've put here 5 row at a table so if my query contain 29 row then it will show on 6 table and last table will contain 4 result the serial no of table will be correctly if first table 1st row is 01 then 2nd table 1st row will be 06. "the query result is not constant but it will depend on database record"
here is my code it shows only 1 table but not showing others table with result.
Thanks for your time. :)
$students = DB::table('mark_prc')
->select('student_roll','mark')
->where('cen_code', $c_code)
->where('sub_code',$subject)
->get();
$k=0; //counter for serial no
$m=5; // no of row each table
$c = count($students); // now have data on array after query 29
$p = ceil($c/5); // the data should be show on 6 tables now
for($i=0;$i<$p;$i++){
echo "<table>
<tr>
<th>SL</th>
<th>Roll</th>
<th>Mark</th>
</tr>";
for($j=$k;$j<$m;$j++){
echo '<tr>
<td>'.($k+1).'</td>
<td>'.$students[$k]->student_roll.'</td>
<td>'.$students[$k]->mark.'</td>
<tr>';
$k++;
}
echo '</table>';
}
Not sure why, but for($j=$k;is doing a reference assignment, so $j=&$k.
A workaround is to do -
for($j=($i*$m);$j<min((($i*$m)+$m),$c);$j++){
The ($i*$m), gets your start value, and ($i*$m)+$m) adds the 'no of row each table'
The min((($i*$m)+$m),$c) in $j<min((($i*$m)+$m),$c) is to max out the loop at $c.
So now your code would look like -
$students = DB::table('mark_prc')
->select('student_roll','mark')
->where('cen_code', $c_code)
->where('sub_code',$subject)
->get();
$m=5; // no of row each table
$c = count($students); // now have data on array after query 29
$p = ceil($c/5); // the data should be show on 6 tables now
for($i=0;$i<$p;$i++){
echo "<table>
<tr>
<th>SL</th>
<th>Roll</th>
<th>Mark</th>
</tr>";
for($j=(($i*$m));$j<min((($i*$m)+$m),$c);$j++){
echo '<tr>
<td>'.($j+1).'</td>
<td>'.$students[$j]->student_roll.'</td>
<td>'.$students[$j]->mark.'</td>
<tr>';
}
echo '</table>';
}
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
Many people will think this is a duplicate question and answers to such question is already given.But I have a different problem, here I don't know the number of columns and name of columns!
I have a text input type in html in which a user can directly manipulate database. User can query any table in database. All tables have different column names and number of columns. And i can't use 'describe' and 'show column' sql statement since name of the column is unknown.
All the answers to this question considers programmer already know column name
and number of columns in table.
So the question is:
how to get number of columns in table?
how to get column names of table to display it in table heading tag?
You can use DESC TABLE_NAME.
Itere the return to know the amount of fields.
Use SHOW COLUMNS FROM your_table_name_here and when you fetch the results the count of the number of rows will tell you how many columns there are.
Part of the data that is returned includes in the name of the columns which you may use for your table headings.
$ColsQ = $yourdb->prepare('SHOW COLUMNS FROM ' . $your_table_name_here);
$ColsQ->execute();
$ColsD = $ColsQ->fetchAll(PDO::FETCH_ASSOC);
echo 'There are ' . count($ColsD) . ' columns in the table';
foreach ($ColsD as $Column) {
echo 'Column name is ' . $Column['Field'];
}
So i got the answer of my question from php documentation! Here i will post snippet of my code which executes 'select' SQL statement written run-time which shows header plus records of table from result i got from executing query.
if(strcmp($words[0], "select")==0) //for making sure its select statement
{
$result= mysqli_query($conn, $sql);
if($result)
{
echo '<table border=1 style="border-collaspe=collaspe" class="table table-striped table-bordered table-hover dataTable no-footer">';
echo '<tr>';
for($i=0;$i<mysqli_num_fields($result);$i++)
{
$column_info=mysqli_fetch_field_direct($result, $i);
/*this function returns all the information about table metioned in the query.
variable i over here refers to field no*/
echo "<th>".$column_info->name."</th>"; //here fetching only name from whole information
}
echo '</tr>';
while ($row = mysqli_fetch_array($result))
{
echo '<tr>';
for($i=0;$i<mysqli_num_fields($result);$i++)
{
echo '<td>'.$row[$i].'</td>';
}
echo '</tr>';
}
echo '</table>';
}
else
{
echo "<script>alert('Error occured, Please check your syntax or internet connection')</script>";
}
}
For detailed information:
PHP Documention page for mysqli_fetch_field_direct ( mysqli_result $result , int $fieldnr ) function
I want to make a timetable in a HTML-table. I have a database structure set up and now I have trouble with displaying the database data in the HTML-table correctly.
My database structure involves:
The days are numbered by day_nr where 1 = monday, 2 = tuesday, 3 = wednesday, 4 = thursday and 5 = friday.
The hours are numbered by hour_nr from 1 to 10.
Here is an example of what I eventually want to create.
Some code:
<?php
session_start();
// Connect MySQL Database
require("function.php");
$con = sql_connection();
// Select data from database (select the right table)
$result01 = mysqli_query("SELECT teacher_code, day_nr, hour_nr, subject_code, room_nr, class_code FROM `lesson`");
echo "<table class='table table-striped table-bordered student_table'>
<thead class='thead-inverse'>
<tr>
<th class='start_time'></th>
<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>
<th>Thursday</th>
<th>Friday</th>
</tr>
</thead>";
You need to create a data structure in your php program representing your time table.
Perhaps you should create an array with an element for each day. Each element of that top level array can itself contain an array, with an element for each time slot in the day.
Then each time slot element can contain an array, with an element for each item to represent in the time slot.
You can then populate this data structure as you retrieve your MySQL result set. You can then render it -- write it to HTML -- using PHP code.
Explaining how to create and use of data structure is, in my opinion, beyond the scope of what you should expect in a Stack Overflow answer.
You have just echoed your table. now you need to echo the actual element in your database for that:
you might consider this
if($num = mysqli_num_rows($result01) > 1){
while($res=mysqli_fetch_assoc[$result01]){
echo "<tr><td>";
echo $res['name of your attribute in the database'];
echo "</td><td></tr>";
}
}
I am trying to display a championship table from the 3 tables I have in my MySQL database.
tbl_champ holds the championship name (nitro) and date (2015). tbl_rounds holds the round name (round1 so on) the date (01/01/2015 so on) and the champ_id. tbl_position holds the round_id, positions (1, 2, 3 etc) and racer_id (2, 4, 8 etc).
Inserting and updating the tables work great, but I cannot seem to get them to display as I want.
This is what I have:
echo '<table border="1">';
$sql_rou = mysql_query("SELECT * FROM `rounds`") or die(mysql_error());
while ($row_rou = mysql_fetch_array($sql_rou)) {
$rid = $row_rou[0];
echo '<th>' . $row_rou[1] . '</th>';
$sql_pos = mysql_query("SELECT `pos_user_id` FROM `positions` WHERE `pos_round_id`='$rid'") or die(mysql_error());
while ($pos_info = mysql_fetch_row($sql_pos)) {
echo '<tr>';
foreach ($pos_info as $field) {
echo '<td>'.$field.'</td>';
}
echo '</tr>';
}
}
echo '</table>';
But I get:
ROUND 1
[20]
[2]
ROUND 2
[2]
[20]
Any way to get the rounds next to each other, but keeping the []'s as they are?
(I've built the table in Excel).
Any ideas? Am I just thinking about this all wrong?
Take a look at where you close the brackets for the <th> entries. It should be about line 6 of your sample code. You have it at the bottom of the page. This will loop every result for each header value.
Also, you don't seem to have any <tr> in your <thead>. Think of your <th> as cells, like <td>, which need to be wrapped in a row.
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..