multiple checkboxes with php in table - php

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.

Related

How to generate HTML table based on group by?

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>';
}
}

How to integrate array_column() and array_filter() into dynamic table generation of sql results

I want to read out data from an sql-database an show them in a table. This works well. Now, I would like to show only those columns with at least one value in it and not the empty ones (containing NULL, 0, empty string). This works with the following example:
enter code here
<TABLE width="500" border="1" cellpadding="1" cellspacing="1">
<?php
$query = mysql_query("SELECT * FROM guestbook", $db);
$results = array();
while($line = mysql_fetch_assoc($query)){
$results[] = $line;
$Name = array_column($results, 'Name');
$Home = array_column($results, 'Home');
$Date = array_column($results, 'Date');
$Emptycolumn = array_column($results, 'Emptycolumn');
$Comment = array_column($results, 'Comment');
$City = array_column($results, 'City');
}
echo "<TR>";
if(array_filter($Name)) {echo "<TH>Name</TH>";}
if(array_filter($Home)){echo "<TH>Home</TH>";}
if(array_filter($Date)){echo "<TH>Date</TH>";}
if(array_filter($Emptycolumn)){echo "<TH>Emptycolumn</TH>";}
if(array_filter($Comment)){echo "<TH>Comment</TH>";}
if(array_filter($City)){echo "<TH>City</TH>";}
echo "</TR>";
$query = mysql_query("SELECT * FROM guestbook", $db);
while($line = mysql_fetch_assoc($query)){
echo "<TR>";
if(array_filter($Name)) {echo "<TD>".$line['Name']."</TD>";}
if(array_filter($Home)) {echo "<TD>".$line['Home']."</TD>";}
if(array_filter($Date)) {echo "<TD>".$line['Date']."</TD>";}
if(array_filter($Emptycolumn)) {echo "<TD>".$line['Emptycolumn']."</TD>";}
if(array_filter($Comment)) {echo "<TD>".$line['Comment']."</TD>";}
if(array_filter($City)) {echo "<TD>".$line['City']."</TD>";}
echo "</TR>";
}
?>
</TABLE>
Since the column-names of my table are highly variable (depending on the query), the table is generated by looping through the result-array, first the column-names, then the values in the rows:
enter code here
$sql = "SELECT DISTINCT $selection FROM $tabelle WHERE
$whereclause"; //will be changed to PDO
$result = mysqli_query($db, $sql) or die("<b>No result</b>"); //Running
the query and storing it in result
$numrows = mysqli_num_rows($result); // gets number of rows in result
table
$numcols = mysqli_num_fields($result); // gets number of columns in
result table
$field = mysqli_fetch_fields($result); // gets the column names from the
result table
if ($numrows > 0) {
echo "<table id='myTable' >";
echo "<thead>";
echo "<tr>";
echo "<th>" . 'Nr' . "</th>";
for($x=0;$x<$numcols;$x++){
$key = array_search($field[$x]->name, $custom_column_arr);
if($key !== false){
echo "<th>" . $key . "</th>";
}else{
echo "<th>" . $field[$x]->name . "</th>";
}
}
echo "</tr></thead>";
echo "<tbody>";
$nr = 1;
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $nr . "</td>";
for ($k=0; $k<$numcols; $k++) { // goes around until there are no
columns left
echo "<td>" . $row[$field[$k]->name] . "</td>"; //Prints the data
}
echo "</tr>";
$nr = $nr + 1;
} // End of while-loop
echo "</tbody></table>";
}
}
mysqli_close($db);
Now, I tried to integrate the array_column() and array_filter()-blocks of the example above into the loops, but unfortunately, it didn´t work. I´m sure, this is easy for a professional and I would be very grateful, if someone could help me with this problem!
Thank you very much in advance!!

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>

SQL Query only displaying first result rather than arrayed data

Basically I am building a calendar page that displays the months, and the days of the month(pulled from my database) and then any days that are inside the "start_date - end_date" variables are displayed with a different cell background color to the days that don't have a start or end date assigned, I have it working to an extent but it's only displaying the earliest of each months record rather than all the results.
ie.
2015-03-12(start) - 2015-03-16(end)
2015-03-03(start) - 2015-03-10(end)
And rather than display like this...
`1 2 [3 4 5 6 7 8 9 10] 11 [12 13 14 15 16] 17 18 19 20 ...`
it's just showing the [3 - 10] record, here is my current code..
<table width="100%" cellspacing="0">
<?php
$cmonth = date('F');
$cyear = date('Y');
$sql = "SELECT * FROM calendar WHERE year = '$cyear' ORDER BY m_order ASC";
$res = mysql_query($sql);
while ($rows = mysql_fetch_array($res)) {
$month_end = $rows['days_in_month'];
$month_name = $rows['month_name'];
$m_order = $rows['m_order'];
$sql2 = "SELECT * FROM trips WHERE start_date LIKE '____-0$m_order-__' ORDER BY start_date ASC";
$res2 = mysql_query($sql2);
$row = mysql_fetch_assoc($res2);
$stdate = $row['start_date'];
$s = date_parse_from_format("Y-m-d", $stdate);
$endate = $row['end_date'];
$e = date_parse_from_format("Y-m-d", $endate);
$start = $s['day'];
$end = $e['day'];
?>
<tr>
<td width="80px"><?php echo $month_name; ?></td>
<?php
foreach(range(1, $month_end) as $days)
{
if(in_array($days, range($start, $end)))
{
echo "<td style=\"background-color: #ccc;\" align=\"center\">" . $days . " </td>";
}
else
echo "<td align=\"center\">" . $days . "</td>";
}
?>
</tr>
<?php } ?>
</table>
Also I am aware of the dangers not using mysqli but I am just learning this on my local machine and plan on researching updated strategies once I get the functions working, so I'll know if my functions are broken or my coding is.
Thanks
try with common function to read data from table
function db_set_recordset($sql) {
$qry = mysql_query($sql);
$row= array();
while($out = mysql_fetch_assoc($qry)) {
$row[] = $out;
}
return $row;
}
$cmonth = date('F');
$cyear = date('Y');
$sql = "SELECT * FROM calendar WHERE year = '$cyear' ORDER BY m_order ASC";
$res = mysql_query($sql);
while ($rows = mysql_fetch_array($res)) {
$month_end = $rows['days_in_month'];
$month_name = $rows['month_name'];
$m_order = $rows['m_order'];
$sql2 = "SELECT * FROM trips WHERE start_date LIKE '____-0$m_order-__' ORDER BY start_date ASC";
$res2 = mysql_query($sql2);
$row = db_set_recordset($res2);
$stdate = $row['start_date'];
$s = date_parse_from_format("Y-m-d", $stdate);
$endate = $row['end_date'];
$e = date_parse_from_format("Y-m-d", $endate);
$start = $s['day'];
$end = $e['day'];
?>
<tr>
<td width="80px"><?php echo $month_name; ?></td>
<?php
foreach(range(1, $month_end) as $days)
{
if(in_array($days, range($start, $end)))
{
echo "<td style=\"background-color: #ccc;\" align=\"center\">" . $days . " </td>";
}
else
echo "<td align=\"center\">" . $days . "</td>";
}
?>
</tr>
<?php } ?>
</table>
You are only fetching one row of your result set from your trips table. You need something like this to get the second one.
while ( $row = mysql_fetch_assoc($res2) ) {
/* process each row */
}
You're doing this right for your other result set. Take a look at the examples here: http://php.net/manual/en/function.mysql-fetch-assoc.php
You'll need to run through the result set rows and accumulate your "hot" days, then render the days just once. Something like this:
$sql2 = "SELECT * FROM trips WHERE start_date LIKE '____-0$m_order-__' ORDER BY start_date ASC";
$res2 = mysql_query($sql2);
while ($row = mysql_fetch_assoc($res2)) {
$stdate = $row['start_date'];
$s = date_parse_from_format("Y-m-d", $stdate);
$endate = $row['end_date'];
$e = date_parse_from_format("Y-m-d", $endate);
$start = $s['day'];
$end = $e['day'];
$hot_days = array();
foreach(range(1, $month_end) as $days) {
$hot_days[$days] = 0;
if(in_array($days, range($start, $end))) {
$hot_days[$days] ++;
}
}
}
/* now you have a $hot_days array with nonzero values for interesting days */
?>
<tr>
<td width="80px"><?php echo $month_name; ?></td>
<?php
foreach(range(1, $month_end) as $day) {
if($hot_days[$day] > 0) {
echo "<td style=\"background-color: #ccc;\" align=\"center\">" . $days . " </td>";
}
else {
echo "<td align=\"center\">" . $days . "</td>";
}
}
?>
</tr>
With respect, I don't have time to debug this.

PHP script generating blank page as output but works fine in WAMP

I am really confused, a script of mine works perfectly in wamp but when i try to run it in my ubuntu apache2 server i get a blank page as output, the same thing happens when i uploaded it to a webserver and executed the script.
I could pinpoint that the error is caused due to the presence of this line of code
while ($row = mysql_fetch_assoc($result))
even if i comment it out the problem persists, only deleting this line will allow me to get any kind of output. Even a simple echo wont work if this line is present.
I am posting the whole script, below may be you people can help me understand the reason behind this strange behavior.
<?php
session_start(); // start up the PHP session!
//Connect to mysql
include 'conn.php';
// Table name
$tbl_name = "tailor.employee";
//Get and initialize variables
$op = $_POST['op'];
$cusid = $_POST['cusid'];
if($op=="2")
{
$sql = "SELECT * FROM tailor.order WHERE cusid ='$cusid'";
$result = mysql_query($sql);
// Mysql_num_row is counting table row
$count = mysql_num_rows($result);
if($count!=0)
{
$order = array();
$oid = array();
$day = array();
$month = array();
$year = array();
$quan = array();
$i=0;
while ($row = mysql_fetch_assoc($result)) {
$cusid = $row['cusid'];
$cname = $row['cname'];
$phone = $row['phone'];
$order[$i] = $row['type'];
$oid[$i] = $row['oid'];
$day[$i] = $row['day'];
$month[$i] = $row['month'];
$year[$i] = $row['year'];
$quan[$i] = $row['quan'];
$i=$i+1;
}
echo "<br><br><br><br><br><br>";
echo "<pre><p><strong>Customer ID : </strong>".$cusid."</pre></p>";
echo "<pre><p><strong>Customer Name : </strong>".$cname."</pre></p>";
echo "<pre><p><strong>Phone Number : </strong>".$phone."</pre></p>";
echo '<table border="1">';
echo "<tr>";
echo "<td>Quantity</td>";
echo "<td>Order ID</td>";
echo "<td>Particulars</td>";
echo "<td>Delivery Date</td>";
echo "</tr>";
echo "<tr><td>";
$icount = count($oid);
for($k=0;$k<$icount;$k++)
{
echo $quan[$k];
echo "<br>";
}
echo "</td>";
echo "<td>";
for($k=0;$k<$icount;$k++)
{
echo $oid[$k];
echo "<br>";
}
echo "</td>";
echo "<td>";
for($j=0;$j<$icount;$j++)
{
echo $order[$j];
echo "<br>";
}
echo "</td>";
echo "<td>";
for($l=0;$l<$icount;$l++)
{
echo $day[$l]."/".$month[$l]."/".$year[$l];
echo "<br>";
}
echo "</td>";
echo "</tr>";
echo "</table>";
echo '<br><br><p ALIGN = "center">Place New Order</p>';
}
unset($_SESSION['cusid']);
unset($_SESSION['oid']);
unset($_SESSION['type']);
unset($_SESSION['cname']);
unset($_SESSION['phone']);
unset($_SESSION['address']);
}
if($op=="1")
{
header('location:order1.html');
}
?>
The app is live and can be accessed by visiting http://www.techb.wilips.com/login.html
The login user name is modern and password is modern#123
To view the error page, just login, add an order and follow the steps then on the 3rd step where you have the Operation drop down menu, select Print Order

Categories