PHP: Building an HTML Table from an Array with Repeated Entries - php

I have a database table (built from a query) that lists member (called Troop), events, start date, and end date. A member might be listed more than once in the table as they are associated with more than one event.
I want to build an HTML table that lists the member's name followed by each event they are associated with before going on to the next member, which may be a few items down in the array.
I was thinking about using aforeach() statement but could not get it to work. Any pointers on how I might accomplish this? Thanks!
while(list($Event, $Troop, $StartDate, $EndDate) = mysqli_fetch_array($result)) {
$return=$return . "<table>";
$return=$return . "<tr>";
$return=$return . "<th colspan=3>" . $Troop . "</th>";
$return=$return . "</tr>";
$return=$return . "<tr>";
$return=$return . "<th>Event</th>";
$return=$return . "<th>Start Date</th>";
$return=$return . "<th>End Date</th>";
$return=$return . "</tr>";
//foreach ($Troop as $thisTroop) {
$return=$return . "<tr>";
$return=$return . "<td>" . $Event . "</td>";
$return=$return . "<td>" . $StartDate . "</td>";
$return=$return . "<td>" . $EndDate . "</td>";
$return=$return . "</tr>";
//}
$return=$return . "</tr>";
$return=$return . "</table>";
}

Replace your code with this. It's necesary that the sql result is sorted by Troop.
$return = '';
$currentTroop = '';
while(list($Event, $Troop, $StartDate, $EndDate) = mysqli_fetch_array($result)) {
if ($currentTroop != $Troop) {
$return .= "<table>"
."<tr>";
."<th colspan=3>" . $Troop . "</th>"
."</tr>"
."<tr>"
."<th>Event</th>"
."<th>Start Date</th>"
."<th>End Date</th>"
."</tr>";
}
$return .= "<tr>"
."<td>".$Event."</td>"
."<td>".$StartDate."</td>"
."<td>".$EndDate."</td>"
."</tr>";
if ($currentTroop != $Troop) {
$return .= "</tr>"
."</table>";
$currentTroop = $Troop;
}
}

Create a multi-dimensional array with keys of Troops and group every records with the same Troop. And then use foreach() to loop the array and print out the information.
Group array by subarray values

Related

Get data from SQL database of multiple columns stored in explode function using PHP

I am using this code to get that data from SQL Server database using PHP
<?php
foreach ($dbDB->query($query) as $row) {
echo "<tr>";
echo "<td>" . $row['Country'] . "</td>";
echo "<td>" . $row['OrderNumber'] . "</td>";
echo "<td>" . $row['Region'] . "</td>";
echo "<td>" . $row['ShipDate'] . "</td>";
echo "<td>" . $row['ProducedDate'] . "</td>";
echo "</tr>"; }
?>
I am trying to replace these multiple lines but storing the columns' names in a string for example $_POST['SelectedColumns'].
The values coming into post as comma separated string, For example : Country,OrderNumber,Region,ShipDate,ProducedDate
I have tried this solution but still not working for me.
<?php
$ser="********";
$db="******";
$user="******";
$pass="******";
$query = 'SELECT '.$_POST['SelectedColumns'].' FROM reporting.REPORT_ALL';
$dbDB = new PDO("odbc:Driver=ODBC Driver 13 for SQL Server;Server=*******;Database=******;Port=1456", $user, $pass);
$row = $_POST["SelectedColumns"];
$rows = explode(",",$row);
/*Here I have the another html code independent of this part */
foreach ($dbDB->query($query) as $dataRow) {
echo "<table>";
echo "<tr>";
foreach ($rows as $r ) {
echo "<td>" . $dataRow[$r] . "</td>"; }
echo "</tr>";
echo "</table>"; }
?>
Any suggestions please ?

php foreach get all data from database table

I would like to get all the values of: echo "<td class=\"points\">" . $row2['PIY'] . "/" . $row2['PIK'] . "</td>"; Some how it only returns the first on. After that i would like to calculate the sum of them.
At the moment the code only gets the first.
echo "<table class=\"zebra\">";
$sum1=0;
$sum2=0;
$numbering =1;
$query2 = "SELECT pisteet_1 As PIY, pisteet_2 as PIK, nimi As NIM, opisto As OPI, pisteet.kaupunki_id As KA FROM
pisteet INNER JOIN joukkueet ON joukkueet.id = pisteet.team_id INNER JOIN oppilaitokset ON oppilaitokset.opisto_id = joukkueet.opisto_id GROUP BY nimi, team_id ORDER BY team_id ASC";
foreach ($db->query($query2) as $row2) {
echo "<tr class=\"all " . $row2['KA'] . "\">";
echo "<td>" . $numbering . "</td>";
echo "<td>" . $row2['NIM'] ."<span>" . $row2['OPI'] ."</span></td>";
//--------should get all the points----------
echo "<td class=\"points\">" . $row2['PIY'] . "/" . $row2['PIK'] . "</td>";
$sum1 +=$row2['PIY'];
$sum2 +=$row2['PIK'];
echo '<td class="Sum">'.$sum1.'/'.$sum2."</td>";
//-------------------------------------------
echo "</tr>";
$numbering ++;
}
echo '</table>';

MySQL row not being ordered in php page

Here you can see the code I use to display a table from a MySQL database in a PHP webpage:
<?php
$con=mysqli_connect("localhost","aaaaaa","bbbbb","my_mk7vrlist");
$x = 1;
$result = mysqli_query($con,"SELECT * FROM 0_vrs_japan ORDER BY `vrs` DESC, `date` ASC");
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $x . "</td>";
echo "<td>" . $row['playername'] . "</td>";
echo "<td><img src='http://mk7vrlist.altervista.org/flags/" . $row['Country'] . ".gif' /></td>";
echo "<td>" . $row['contactable'] . "</td>";
echo "<td>" . $row['vrs'] . "</td>";
if($row['date'] != "-"){
$formatted = date('jS F Y', strtotime($row['date']));
} else {
$formatted = "-";
}
if($row['pic'] != "-"){
echo "<td>" . $formatted . "</td>";
} else {
echo "<td>" . $formatted . "</td>";
}
echo "</tr>";
$x = $x+1;
}
mysqli_close($con);
?>
And the result is this:
Every player with 99'999 points (which are called 'vrs') is sorted by the date. I am having troubles with that player I have just added.
His date 2014/05/22 in the database isn't in the correct position (after Megaman). Do you have any idea?
You're storing the date as a varchar so MySQL is having trouble sorting it in the way you need it to, as it's sorting lexicographically with the field being a varchar.
Convert them to proper date fields and natural date sorting will work as intended.

Find last value of array in foreach cicle

I've data stored in a array ($rows).
For read the array and genarate a dinamic table I use foreach function.
<table>
foreach ($rows as $row) {
echo "<tr>";
echo "<td>" . $row['field1'] . "</td>";
echo "<td>" . $row['field2'] . "</td>";
echo "<td>" . $row['filed3'] . "</td>";
echo "</tr>";
}
</table>
My goal is to find the last value of the array (the end) in order to change the class of TR element for the last line displayed.
How could I do this?
Thanks
Try this:
foreach ($rows as $key => $row) {
$end = end($rows) === $row ? 'class="last"' : '';
echo "<tr $end>";
echo "<td>" . $row['field1'] . "</td>";
echo "<td>" . $row['field2'] . "</td>";
echo "<td>" . $row['filed3'] . "</td>";
echo "</tr>";
}
This method works for multidimentional arrays as well.
http://codepad.org/HQG9ytBX
Edit. As pointed in comments, this approach may potentially trigger false end result if some values in the array are duplicated (with the last). Correct bullet-proof version should be:
foreach ($rows as $key => $row) {
$end = end($rows) === $row && $key === key($rows) ? 'class="last"' : '';
// ...
foreach ($rows as $row) {
$is_last_row = ++$i == count($rows);
echo "<tr>";
echo "<td>" . $row['field1'] . "</td>";
echo "<td>" . $row['field2'] . "</td>";
echo "<td>" . $row['filed3'] . "</td>";
echo "</tr>";
}
here $i should be an unused variable.
Try This
$numItems = count($rows);
$i = 0;
foreach($rows as $row) {
$trClass = 'firstclass';
if(++$i === $numItems)
{
$trClass = 'lastclass';
}
echo "<tr class='$trclass'>";
echo "<td>" . $row['field1'] . "</td>";
echo "<td>" . $row['field2'] . "</td>";
echo "<td>" . $row['filed3'] . "</td>";
echo "</tr>";
}
// first, let's find out the last key
end($rows);
$last = key($rows);
// then just loop over
foreach ($rows as $key => $row) {
if ($key == $last) {
// last leaf of the summer...
}
echo "<tr>";
echo "<td>" . $row['field1'] . "</td>";
echo "<td>" . $row['field2'] . "</td>";
echo "<td>" . $row['filed3'] . "</td>";
echo "</tr>";
}

PHP - How do I get this to print out in a table from an reference number?

echo '<td><input type="checkbox" name="items[]" value="' . $row['0'] . '" /></td>';
Hi, I'm trying to get a reference number which comes from a an array called items from another page as shown above, and to find it in the table and print out the reference row, like "Title,Platform...." into another table, but I can't seem to get it working...any help be appreciated
if (isset($_POST['items'])) {
$n = count($_POST['items']);
for($i=0; $i < $n; $i++){
// echo $_POST['items'][$i];
}
$items = array();
foreach ($_POST['items'] as $item) {
$items[] = pg_escape_string($con, $item);
}
if (!$_SESSION["selectingrows"]) {
$item_string = "'" . implode("','", $items) . "'";
$result = pg_query ($con, "SELECT title, platform, description, price FROM CSGames WHERE 'refnumber' IN ($item_string)");
while($rows = pg_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $rows['1'] . "</td>";
echo "<td>" . $rows['2'] . "</td>";
echo "<td>" . $rows['3'] . "</td>";
echo "<td>" . $rows['4'] . "</td>";
echo "</tr>";
}
}
}
One thing, you need to put {} braces after your while loop.
Here is what you are doing:
while($rows = pg_fetch_assoc($result))
echo"<tr>"; echo "<td>" . $rows['1'] . "</td>"; echo "<td>" . $rows['2'] . "</td>"; echo "<td>" . $rows['3'] . "</td>"; echo "<td>" . $rows['4'] . "</td>";
echo"</tr>";
By not putting braces around the code after the while statement, here is what your code really does:
while($rows = pg_fetch_assoc($result))
{
echo"<tr>";
}
echo "<td>" . $rows['1'] . "</td>"; echo "<td>" . $rows['2'] . "</td>"; echo "<td>" . $rows['3'] . "</td>"; echo "<td>" . $rows['4'] . "</td>";
echo"</tr>";
You should always put braces in to define what code is in the while loop.
You want your code to be something like this:
while($rows = pg_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $rows['1'] . "</td>";
echo "<td>" . $rows['2'] . "</td>";
echo "<td>" . $rows['3'] . "</td>";
echo "<td>" . $rows['4'] . "</td>";
echo "</tr>";
}
Format your code neatly and properly. By doing this your code is clearer and it is much easier to notice possible mistakes like the above. Always use braces for if, while, for statements. When putting an end line semicolon ; put in a new line break. Indent your code correctly. It's little things like formatting that make coding easier.
Now the next problem I can see is the values you are getting from the $rows array:
$rows['1'];
$rows['2'];
$rows['3'];
$rows['4'];
This is trying to get something from the $rows array which has the key of string '1'.
Usually you access array values by index, which uses an integer beggining from 0. Or you access it by a key.
Either you can try this:
$rows[0];
$rows[1];
$rows[2];
$rows[3];
Or this:
$rows['title'];
$rows['platform'];
$rows['description'];
$rows['price'];

Categories