How to generate HTML table based on group by? - php

I am trying to create very simple time tracking app with only 3 values in database: description, time-spent and date and I need to group results by Date and generate HTML tables.
For example:
Today(10.07) for this date I have 3 records in database, I need to generate HTML table for this date.
Tommorow(11.07) when I create new record with new date - it creates new HTML table.
At the and I have a lot of HTML tables with specific day dates.
(HTML table for its own date).
So how to group by date and how to generate HTML tables?
The screenshot below reflects what I'm trying to achieve:
Below is my code:
function getLogs( $con ) {
$stmt = $con->prepare( "SELECT * FROM timelogsapp GROUP BY DATE ORDER BY date DESC" );
$stmt->execute();
$result = $stmt->fetchAll();
foreach( $result as $row ) {
echo '<table class="list-table">';
echo '<thead>';
echo '<span class="date">';
echo datetime();
echo '</span>';
echo '<tr>';
echo '<th>Description</th>';
echo '<th>Time</th>';
echo '<th>Date</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
echo '<tr>';
echo '<td>' . $row['description'] . '</td>';
echo '<td>' . $row['time'] . '</td>';
echo '<td>' . $row['date'] . '</td>';
echo '</tr>';
echo '</tbody>';
echo '</table>';
}
}

You can create a SQL WHERE the dates are within the wanted range. So you said you wanted to be for today, it would look like this:
UPDATE
This should create multiple queries and you can Add more to the WHERE clause, to get the custom date, I hope this gives you an idea of what you can do with.
Every record will create it's unique table, as they are inside of the foreach clause.
<?php
$today = date('d.m');
$today_query = "SELECT * FROM timelogsapp WHERE date = $today DESC";
$yesterday = date('d.m', time() - 60 * 60 * 24);
$yesterday_query = "SELECT * FROM timelogsapp WHERE date = $yesterday DESC";
$custom = "";
if (isset($_POST['date']))
{
$custom = $_POST['date'];
}
$custom_query = "SELECT * FROM timelogsapp WHERE date = $custom DESC";
$tom = new DateTime('tomorrow');
$tomorrow = $tom->format('d.m');
$tomorrow_query = "SELECT * FROM timelogsapp WHERE date = $tomorrow DESC";
function getLogs($con){
$stmt = $con->prepare("SELECT * FROM timelogsapp WHERE date = $today AND date = $yesterday AND date = $custom DESC");
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row) {
echo '<table class="list-table">';
echo '<thead>';
echo '<span class="date">';
echo datetime();
echo '</span>';
echo '<tr>';
echo '<th>Description</th>';
echo '<th>Time</th>';
echo '<th>Date</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
echo '<tr>';
echo '<td>'.$row['description'].'</td>';
echo '<td>'.$row['time'].'</td>';
echo '<td>'.$row['date'].'</td>';
echo '</tr>';
echo '</tbody>';
echo '</table>';
}
}
?>
Of course you can make that much more dynamic by playing with some PHP. But that will select all records from timelogsapp just where the dates equal to 10.07. Then display it in descending order.

I managed to achieve the result i've been looking for.
// getting all dates from database with limit
$all_dates_query = "SELECT * FROM timelogsapp GROUP BY date(date) ORDER BY date DESC LIMIT $limit OFFSET $offset";
$stmt = $con->prepare($all_dates_query);
$stmt->execute();
$all_dates = $stmt->fetchAll();
function getLogs($con, $all_dates)
{
foreach ($all_dates as $row) {
$this_date = $row['date'];
$all_dates = "SELECT * FROM timelogsapp WHERE date(date) = date('$this_date') ORDER BY date DESC"; //getting all logs for current date
$stmt = $con->prepare($all_dates);
$stmt->execute();
$result = $stmt->fetchAll();
//generating html table with logs
echo '<table class="list-table">';
echo '<thead>';
echo '<span class="date">';
echo datetime($this_date);
echo '</span>';
echo '<tr>';
echo '<th>Description</th>';
echo '<th>Time</th>';
echo '<th>Date</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
foreach ($result as $row) {
echo '<tr>';
echo '<td>'.$row['description'].'</td>';
echo '<td>'.$row['time'].'</td>';
echo '<td>'.date('d.m.Y H:i', strtotime($row['date'])).'</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
}
}

Related

Two articles in my php array

I'm trying to make a webshop for an assignment and I can't figure out how to display that there are 2 of the same product in my checkout. This is my code I want to display something like: Article1 .. 2x Article2 ... 5x etc.
<?php
session_start();
//read out session with article numbers
$array = $_SESSION['mandje'];
echo '<center>';
echo '<h1> Uw mandje: </h1>';
echo '<table style="border: 2px solid black">';
//array that checks if there are two of the same article numbers
$mandje = array();
//read out array
foreach ($array as $artikel)
{
echo '</br>';
echo $artikel;
if (in_array($artikel, $mandje)){
//I need to display the article that i have multiple times here i guess
} else {
//getting the articles out of the database
require ('config.php');
$query = "SELECT * FROM mphp6_meubels WHERE artikelnr = $artikel";
$results = mysqli_query($mysqli, $query);
while($meubel = mysqli_fetch_array($results)){
$video = $meubel['naam'];
$nmr = $meubel['artikelnr'];
echo '<tr>';
echo '<td> <img src="Meubels/'.$video.'.jpg" width="150" height="150" alt="Meubel"></td>';
echo '</tr>';
}
}
//adding the article to array so i can check if there are multiple of the same articles in array
$mandje[] = $artikel;
}
echo '</table>';
echo '</center>';
Just group by artikelnr field.
foreach ($array as $artikel)
{
require ('config.php');
$query = "SELECT mphp6_meubels.*, count(*) as cnt FROM mphp6_meubels WHERE artikelnr = $artikel GROUP BY artikelnr";
$results = mysqli_query($mysqli, $query);
while($meubel = mysqli_fetch_array($results)){
$video = $meubel['naam'];
$nmr = $meubel['artikelnr'];
echo '<tr>';
echo '<td>' . $artikel . '</td>';
echo '<td> <img src="Meubels/'.$video.'.jpg" width="150" height="150" alt="Meubel"></td>';
echo '<td> ' . $meubel['cnt'] . '</td>';
echo '</tr>';
}
}

Writing the attributes of a database in PHP

I am writing an application in which user can enter a database name and I should write all of its contents in table with using PHP.I can do it when I know the name of database with the following code.
$result = mysqli_query($con,"SELECT * FROM course");
echo "<table border='1'>
<tr>
<th>blablabla</th>
<th>blabla</th>
<th>blablabla</th>
<th>bla</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['blabla'] . "</td>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['bla'] . "</td>";
echo "</tr>";
}
echo "</table>";
In this example I can show it since I know the name of table is course and it has 4 attributes.But I want to be able to show the result regardless of the name the user entered.So if user wants to view the contents of instructors there should be two columns instead of 4.How can I accomplish this.I get the table name with html.
Table:<input type="text" name="table">
Edit:Denis's answer and GrumpyCroutons' answer are both correct.You can also ask me if you didnt understand something in their solution.
Quickly wrote this up, commented it (This way you can easily learn what's going on, you see), and tested it for you.
<form method="GET">
<input type="text" name="table">
</form>
<?php
//can be done elsewhere, I used this for testing. vv
$config = array(
'SQL-Host' => '',
'SQL-User' => '',
'SQL-Pass' => '',
'SQL-Database' => ''
);
$con = mysqli_connect($config['SQL-Host'], $config['SQL-User'], $config['SQL-Pass'], $config['SQL-Database']) or die("Error " . mysqli_error($con));
//can be done elsewhere, I used this for testing. ^^
if(!isSet($_GET['table'])) { //check if table choser form was submitted.
//In my case, do nothing, but you could display a message saying something like no db chosen etc.
} else {
$table = mysqli_real_escape_string($con, $_GET['table']); //escape it because it's an input, helps prevent sqlinjection.
$sql = "SELECT * FROM " . $table; // SELECT * returns a list of ALL column data
$sql2 = "SHOW COLUMNS FROM " . $table; // SHOW COLUMNS FROM returns a list of columns
$result = mysqli_query($con, $sql);
$Headers = mysqli_query($con, $sql2);
//you could do more checks here to see if anything was returned, and display an error if not or whatever.
echo "<table border='1'>";
echo "<tr>"; //all in one row
$headersList = array(); //create an empty array
while($row = mysqli_fetch_array($Headers)) { //loop through table columns
echo "<td>" . $row['Field'] . "</td>"; // list columns in TD's or TH's.
array_push($headersList, $row['Field']); //Fill array with fields
} //$row = mysqli_fetch_array($Headers)
echo "</tr>";
$amt = count($headersList); // How many headers are there?
while($row = mysqli_fetch_array($result)) {
echo "<tr>"; //each row gets its own tr
for($x = 1; $x <= $amt; $x++) { //nested for loop, based on the $amt variable above, so you don't leave any columns out - should have been <= and not <, my bad
echo "<td>" . $row[$headersList[$x]] . "</td>"; //Fill td's or th's with column data
} //$x = 1; $x < $amt; $x++
echo "</tr>";
} //$row = mysqli_fetch_array($result)
echo "</table>";
}
?>
$tablename = $_POST['table'];
$result = mysqli_query($con,"SELECT * FROM $tablename");
$first = true;
while($row = mysqli_fetch_assoc($result))
{
if ($first)
{
$columns = array_keys($row);
echo "<table border='1'>
<tr>";
foreach ($columns as $c)
{
echo "<th>$c</th>";
}
echo "</tr>";
$first = false;
}
echo "<tr>";
foreach ($row as $v)
{
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
<?php
$table_name = do_not_inject($_REQUEST['table_name']);
$result = mysqli_query($con,'SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME='. $table_name);
?>
<table>
<?php
$columns = array();
while ($row = mysql_fetch_assoc($result)){
$columns[]=$row['COLUMN_NAME'];
?>
<tr><th><?php echo $row['COLUMN_NAME']; ?></th></tr>
<?php
}
$result = mysqli_query($con,'SELECT * FROM course'. $table_name);
while($row = mysqli_fetch_assoc($result)){
echo '<tr>';
foreach ($columns as $column){
?>
<td><?php echo $row[$column]; ?></td>
<?php
}
echo '</tr>';
}
?>
</table>

php mysql select data to gridview

when select data from database using php-mysql and display in html table it shows as (A).
but i want to display it as (b)
help me...
Sample (and very simple) code would be:
// assuming the PDO connection is established and kept in $db
$st = $db->prepare("SELECT Date, Num, Value1, Value2 FROM the_table");
if ($st->execute()) {
$previousDate = NULL;
$previousNum = NULL;
while ($row = $st->fetch()) {
echo '<tr>';
echo '<td>';
if ($previousDate != $row['Date']) {
echo $row['Date'];
$previousDate = $row['Date'];
}
echo '</td>';
echo '<td>';
if ($previousNum != $row['Num']) {
echo $row['Num'];
$previousNum = $row['Num'];
}
echo '</td>';
echo '<td>'. $row['Value1'] .'</td>';
echo '<td>'. $row['Value2'] .'</td>';
echo '</tr>';
}
}

multiple checkboxes with php in table

I'm trying to build a simple attendance script which has the members in the users table. I have a script which builds the table and shows me today's date along with the rest of the month.
I also have a script which prints out the individual users, along side these users I want to have a checkbox in every column as far as the dates stretch out to.
I have a foreach statement for printing the users however if I put the <td><input type="checkbox"/></td> into this foreach statement this is only filling in the first column of dates.
If I put it in the for statement which outputs my <th> dates then it appends the checkbox in the <th> which is not what I want.
I'm not the best programmer so I'm not sure of the method that I should be using to achieve this, what I've done is simple so far if you look below you will be able to see how I've achieved this:
To reitrate the problem is that I am unable to append a checkbox per date value from the code below which prints dates from today's date to whatever it is set to.
Any ideas or input gladly welcomed.
public function viewall() {
$sth = $this->db->prepare("SELECT * FROM users");
$sth->execute();
/* Fetch all of the values of the first column */
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
$startDate = new DateTime();
$endDate = new DateTime('2013-09-31');
$days = array();
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>";
for ($c = $startDate; $c <= $endDate; $c->modify('+1 day')) {
echo "<th>".$c->format('d')."</th>"; }
echo "</tr>";
foreach($result as $row) {
$firstname = $row['firstname'];
$lastname = $row['lastname'];
echo "<tr>";
echo "<td>$firstname</td>";
echo "<td>$lastname</td>";
}
echo "<td><input type='checkbox'/></td></tr>";
echo "</table>";}
PICTURE 1 SHOWS THE PROBLEM
PICTURE 2 SHOWS HOW IT SHOULD LOOK
Here is the solution based on screen shots.
<?php
public function viewall() {
$sth = $this->db->prepare("SELECT * FROM users");
$sth->execute();
/* Fetch all of the values of the first column */
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
$startDate = new DateTime();
$endDate = new DateTime('2013-09-31');
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>";
for ($c = clone $startDate; $c <= $endDate; $c->modify('+1 day')) {
echo "<th>".$c->format('d')."</th>";
}
echo "</tr>";
foreach($result as $row) {
echo "<tr>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
for($c = clone $startDate; $c <= $endDate; $c->modify('+1 day')) {
echo "<td><input type='checkbox'/></td>";
}
echo "</tr>";
}
echo "</table>";
}
?>
EDIT: added clone to copy the object correctly
I am not very clear about your problem, but I think the following codes may help:
public function viewall()
{
$sth = $this->db->prepare("SELECT * FROM users");
$sth->execute();
/* Fetch all of the values of the first column */
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
$startDate = new DateTime();
$endDate = new DateTime('2013-09-31');
$days = array();
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>";
for ($c = $startDate; $c <= $endDate; $c->modify('+1 day'))
{
echo "<th>" . $c->format('d') . "</th>";
}
echo "</tr>";
foreach ($result as $row)
{
$firstname = $row['firstname'];
$lastname = $row['lastname'];
echo "<tr>";
echo "<td>$firstname</td>";
echo "<td>$lastname</td>";
$startDate = new DateTime();
$endDate = new DateTime('2013-09-31');
for ($c = $startDate; $c <= $endDate; $c->modify('+1 day'))
{
echo "<td><input type='checkbox'/></td>";
}
echo "</tr>";
}
echo "</table>";
}
I can not access db, so I cann't test it, what I want to say is that, tr or th stand for a table line, td is children, every line's children's count should be same.

Numerating Comments

The code below prints out all comments for a given "submissionid" in chronological order. How could I numerate these comments? (In other words, how do I print out a "1." next to the oldest comment, a "2." next to the second-oldest comment, etc.?)
$submission = mysql_real_escape_string($_GET['submission']);
$submissionid = mysql_real_escape_string($_GET['submissionid']);
$sqlStr = "SELECT comment.comment, comment.datecommented, login.username
FROM comment
LEFT JOIN login ON comment.loginid=login.loginid
WHERE submissionid=$submissionid
ORDER BY comment.datecommented ASC
LIMIT 100";
$result = mysql_query($sqlStr);
$arr = array();
echo "<table class=\"commentecho\">";
while ($row = mysql_fetch_array($result)) {
echo '<tr>';
echo '<td class="commentname1">'.stripslashes($row["comment"]).'</td>';
echo '</tr>';
echo '<tr>';
echo '<td class="commentname2">'.$row["username"].''.date('l, F j, Y &\nb\sp &\nb\sp g:i a &\nb\sp &\nb\sp \N\E\W &\nb\sp \Y\O\R\K &\nb\sp \T\I\M\E', strtotime($row["datecommented"])).'</td>';
echo '</tr>';
}
echo "</table>"
Showing relevant part of code, rest commented out so you immediately see what i added:
//echo "<table class=\"commentecho\">";
$count = 1; //<-start counter
//while ($row = mysql_fetch_array($result)) {
//echo '<tr>';
echo '<td>'.$counter++.'</td>'; //<-use numbering and increment afterwards
//echo '<td class="commentname1">'.stripslashes($row["comment"]).'</td>';
//echo '</tr>';
//..
}
//echo "</table>";

Categories