Display data from database vertically in table - php

<?php
echo "<table class=\"table table-hover table-bordered\">";
echo "<thead>";
echo "<tr>";
$result=mysqli_query($con,"SELECT day FROM time_slot ORDER BY day;");
while($row=mysqli_fetch_array($result))
{
$days = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
$day = $row['day']-1;
$day = $days[$day];
echo '<th>';
echo $day;
echo '</th>';
}
echo "</tr>";
echo "</thead>";
require('../includes/connection.php');
$result=mysqli_query($con,"SELECT * FROM time_slot ORDER BY day DESC;");
while($row=mysqli_fetch_array($result))
{
echo "<tbody>";
echo "<tr>";
This portion of data should be display vertically in table with respect to Day
//This code to split time into intervals
$starttime = $row['start_time']; // your start time
$endtime = $row['end_time']; // End time
$duration = $row['slot_time'];
$array_of_time = array ();
$start_time = strtotime ($starttime); //change to strtotime
$end_time = strtotime ($endtime); //change to strtotime
$add_mins = $duration * 60;
while ($start_time <= $end_time) // loop between time
{
echo '<td>';
echo "<div align=\"center\">";
print_r(date ("h:i", $start_time) ."-". date("h:i", $start_time += $add_mins));
//
echo "</br><input type=\"radio\" name=\"texi\" value=\"1\" ></input>";
echo '</td>' ;
echo '</div>';
}
echo "</tr>";
echo "</tbody>";
}
mysqli_close($con);
echo "</table>
</div>
<input type=\"submit\" value=\"Book Slot\" class=\"button_drop\">
</form>";
?>
I want to show time slots vertically with respect to day in table.
This is the output of this code:
But I want to display time which is showing horizontally that should be shown vertically. Eg. 1-3, 3-5, 5-7 of first row should be shown below Monday, then next row should be shown below Tuesday and so on.

Try using a query like this:
SELECT day FROM time_slot ORDER BY time_slot, day;
That should get the data in an easier order to process. I can't see your exact data structure but it looks like you should get 7x 01:00-03:00, then 7x 03:00-05:00 etc. Each set should be in order by day. Then you can just write out your <td>s in the order the data comes from the DB. Keep track of when the day value changes (or just count up to 7) and start a new <tr> at that time.

Related

I want to show column status ex.if day left has 30 days status it danger

I want status to have a relation with day_left, e.g. if day_left has 30 days status should be danger. This is homework
<?php
$con2= mysqli_connect("localhost","root","root","database") or die("Error: " . mysqli_error($con2));
$query2 = "SELECT *,datediff (mainexpire,now()) as day_left from contact";
$result2 = mysqli_query($con2, $query2);
echo "<table border='1' align='center' width='1000'>";
echo "<tr bgcolor='#FFFACD'><td><p><center><b>no</center></td></p></b><td><p><center><b>maintenance items
</center></td></p></b><td><p><center><b>owner
</td></p></center></b>
<td><p><center><b>detail
</center></td></p></b><td><p><center><b>expire_date
</center></td></p></b><td><p><center><b>Days Left
</center></td></p></b><td><p><center><b>Status
</center></td></p></b>
</tr>";
while($row2 = mysqli_fetch_array($result2)) {
echo "<tr>";
echo "<td><center><p>" .$row2["no"] . "</center></td></p> ";
echo "<td><center><p>" .$row2["mainitem"] . "</center></td></p> ";
echo "<td><center><p>" .$row2["mainowner"] . "</center></td></p> ";
echo "<td><center><p>" .$row2["maindetail"] . "</center></td></p> ";
echo "<td><center><p>" .$row2["mainexpire"] . "</center></td></p> ";
echo "<td><center><p>" .$row2["day_left"] . "</center></td></p> ";
}
?>
</body>
Well you are doing good with that homework (if you did that of your own, of course). Just need to add a if else condition for the status. Some thing like this after the last line of your while loop.
if( $row2["day_left"] > 30 ) {
echo "<td><center><p>All OK</center></td></p> ";
} else {
echo "<td><center><p>Danger</center></td></p> ";
}
function day_left($day){ //$day will be the target date
$target_date= strtotime($day); //this convert the target day to second
$today = strtotime("today"); //this convert the current day to second
$day_sec = $target_date- $today; //so target day minus current day second
$total_day_left = $day_sec / 86400; //divide it to 86400 thats equivalent to one day
return $total_day_left; //the total day left
}

Create a cumulative comparison table in PHP and MySql

I have a database table called payments which contains date,amount fields. I want to take values from amount field and SUM up all amounts by date and take the results to html table then output them like on the image.
I have created dates dynamically so that they will be equal nomatter which months example January its 1-31 and February its 1-31. Where there is a weekend or the date is invalid i want the value to be zero. What i want is like this table [table][1] [1]: http://i.stack.imgur.com/iMOl3.jpg
This is what i am getting [output][1][1]: http://i.stack.imgur.com/MJpyT.jpg
******NOTE***** I THINK MY SOLUTION IS NOT THE BEST SOLUTION TO MY PROBLEM. IF POSSIBLE JUST TAKE I VIEW ON THE PICTURE WHICH I WANT AND FIND ME THE BEST SOLUTION. I WANT TO BE HELPED IN EITHER STEPS TO ACHIEVE IT OR A SOLUTION
I know that i am using a depricated mysql synthax please ignore that and help on my problem.
<table border="1" align="center">
<?php
session_start();
include("connection/db_con.php");
$sym='-';
$d=array();
///Insert values of month for period selected into an array
$a = $_POST['dat'];
$b = $_POST['dat2'];
$mnth=array();
$m_nam=array();
$m_nm=array();
$m_nam[]="Day";
//////New way of getting months in format Y-m
$start = new DateTime($a);
$start->modify('first day of this month');
$end = new DateTime($b);
$end->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
$mnth[]=$dt->format("Y-m");
$m_nam[]=date('F-Y', strtotime($dt->format("Y-m")));
$m_nm[]=date('M', strtotime($dt->format("Y-m")));
}
///////End of New way
echo "<tr bgcolor='#999999'>";
foreach ($m_nam as $m)
{
echo"<td>".$m."</td>";
}
echo"</tr>";
/////////End insert////////////////////////
$day=0;
for($x=1; $x<=31; $x++)
{
$day=$day+1;
echo"<tr>";
echo"<td>".$day."</td>";
$d=$sym.$x;
foreach($mnth as $mon)
{
$dat=$mon.$d;
$qry=mysql_query("SELECT SUM(amount) AS total_disb FROM payments where dat='$dat'")or die(mysql_error());
$row=mysql_fetch_assoc($qry);
$sum = $row['total_disb']+0;
echo"<td>".$sum."</td>";
}
echo"</tr>";
}
?>
</table>
Here's a rewrite of the code you provided, it's using dummy random data instead of DB and there is no logic for POST variables, but that you can replace with your code.
<?php
// session start, db connection goes here
echo '<table border="1" align="center">';
// Example of post vars
$start = new DateTime('2015-11-10');
$end = new DateTime('2016-02-28');
// Note: not sure why OP used modify here
$interval = new DateInterval('P1M');
$daterange = new DatePeriod($start, $interval, $end);
// Table Header row 1
echo '<tr><th>Day</th>';
foreach ($daterange as $date) {
echo '<th colspan="2">'.$date->format("F Y").'</th>';
}
echo '</tr>';
// Temporary month store
$months = array();
// Table Header row 2
echo '<tr style="background-color:#22bb22;"><th></th>';
foreach ($daterange as $date) {
$months[] = $date->format("F");
echo '<th>Daily</th>';
echo '<th>Cumulative</th>';
}
echo '</tr>';
// Table Body
$sumc = array();
for ($d = 1; $d <= 31; $d++) {
echo '<tr><td>'.$d.'</td>';
foreach ($months as $month) {
$db_date = $month.'-'.$d; // used for db query
// dummmy data (replace with db query result)
$sum = mt_rand(0, 999);
echo '<td>'.$sum.'</td>';
if(!array_key_exists($month, $sumc)) {
$sumc[$month] = 0;
}
$sumc[$month] = (int)$sum + $sumc[$month];
echo '<td>'.$sumc[$month].'</td>';
}
echo '</tr>';
}
echo '</table>';
?>
Also the condition:
Where there is a weekend or the date is invalid i want the value to be
zero.
is it correct to assume that these are taken care because the DB query would return 0? Or do you have to check in the code for weekends even if the DB query returns an amount from total_disb that is >0?
You have just messed up a little with dates, if I'm understanding where your problem is you can do it directly from SQL, try something like:
SELECT SUM(amount) AS total_disb , MONTH(DateTime) , DAY(DateTime)
FROM payments
GROUP BY DATE(DateTime), DAY(DateTime)
Change DateTime for your variable or column names.
If you also want to SUM the months totals at the end of the table I'd recommend you to make a new query like:
SELECT SUM(amount) AS total_disb , MONTH(DateTime)
FROM payments
GROUP BY DATE(DateTime), MONTH(DateTime)
Another option would be to increment a variable while you loop to print the values, but in my opinion a new query is more simple.
If this is not what you need leave a comment and I will edit it.
To get to the cumulative you have to store the previous sum result and add it to the current iteration in the loop, something like:
$sumc = array();
foreach($mnth as $mon) {
$dat = $mon . $d;
$qry = mysql_query("SELECT SUM(amount) AS total_disb FROM payments where dat='$dat'") or die(mysql_error());
$row = mysql_fetch_assoc($qry);
$sum = $row['total_disb'];
if(isset($sumc[$mon])) {
$sumc[$mon] = (int)$sum + $sumc[$mon];
} else {
$sumc[$mon] = (int)$sum;
}
echo "<td>" . $sum . "</td>";
echo "<td>" . $sumc[$mon] . "</td>";
}
should probably work.
(Note: that you are missing a second row for 'daily' and 'cumulative' and once you have that row you need to use colspan to span the columns of the Months across). See an example of colspan here.

Convert Unix TimeStamp into "x seconds ago"

so I have a table which lists chat messages in my game server (chat messages are stored in a database) and I have a UNIX timestap like this (for example) 1455749769
Does anyone know how I can use php to convert the timestamp so it echos how long ago the chat message was for example: "5 Seconds Ago"
Here is my table
$name=$row['client_name'];
$time=$row['msg_time'];
$name=htmlentities($name);
echo "<tr>";
echo "<td> $time </td>";
echo "<td><a href='http://144.76.158.173/ech/user.php?id=".$row["client_id"]."' > $name </a></td>";
echo "<td> $msg </td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
echo "</div>";
}
$conn->close();
?>
Any help greatly appreciated :)
The timestamp is seconds since the Epoch, so just get the current timestamp and subtract:
$seconds = time() - $time
Just get the current time and substract:
$now = time();
//results into an unix like 1455750460
//then just substract:
$diff = $now - $time
// gives you the passed seconds
//readable
echo date('H:i:s', $diff);

Calculate days between 2 dates and another criterial PHP MYSQL

I'm new newbie to programming and I've got an error that i wasn't able to solve after hours searching.
I'm using a form to perform a search and display in a table the data, that part was fairly easy... but I also want to calculate how many days are in the final result, not in the dates I using for the first query.
The query searches for the result in days between 2 dates and from a specified company, the problem is in the final result it calculates how many days are from my result and not from the days i searched.
Example: If i search 2 dates between February 11 and February 20 Where the company = 1
If there is only 3 days result for Company 1, I want it to calculate only 3 Days.
I know my code is Wrong in that part but i just can't get it to do what i want.
Here is a little piece of my code to explain it:
if (isset($_POST['search'])) {
$date1 = mysql_prep($_POST['date1']);
$date2 = mysql_prep($_POST['date2']);
$latte = mysql_prep($_POST['latte']);
$query = "SELECT * FROM payroll WHERE (day BETWEEN '{$date1}' AND '{$date2}') AND (company = '{$latte}') ORDER BY day ASC ";
$result = mysql_query($query, $connection);
$woof = "SELECT SUM(hours) FROM (SELECT * FROM payroll WHERE (day BETWEEN '{$date1}' AND '{$date2}') AND (company = '{$latte}') ORDER BY day ASC) AS subt ";
$raw = mysql_query($woof, $connection);
if(!$raw) { die(mysql_error());}
$meow = mysql_result($raw, 0, 0);
$diff = abs(strtotime($date2) - strtotime($date1));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24) +1);
if(!$result) {
echo "FAIL";
} else {
echo "<table>
<tr>
<th> Date </th>
<th> Hours </th>
<th> Job Title </th>
<th> Job Description </th>
<th> Paid </th>
<th> For </th>
</tr>";
while($row = mysql_fetch_array($result))
{
$company = $row['company'];
if($company == 0) {
$company = "Wilson Electric";
} if($company == 1) {
$company = "Wilson Rental";
} if ($company == 2) {
$company = "Church of Christ";
}
echo "<tr>";
echo "<td class=\"center\">" . $row['day'] . "</td>";
echo "<td class=\"center\">" . $row['hours'] . "</td>";
echo "<td style=\"padding:5px;\">" . $row['job_title'] . "</td>";
echo "<td style=\"padding:5px;\">" . $row['job_description'] . "</td>";
echo "<td class=\"center\">" . $row['paid'] . "</td>";
echo "<td style=\"padding:5px;\">" . $company . "</td>";
echo "</tr>";
}
echo "<tr>";
echo "<td class=\"center\"> Total Days: " . $days . "</td>";
echo "<td class=\"center\"> Total Hours: " . $meow . "</td>";
echo "</tr>";
}
}
Thanks for Reading it, I hope someone can give me a solution, i know must be something really simple but I just couldn't figure out.
If you want a count of distinct day values that match the specification, then you could add a simple expression to the SELECT list of the "woof" SQL statement:
SELECT SUM(hours), COUNT(DISTINCT `day`) AS cnt_days FROM ...
$meow = mysql_result($raw, 0, 0);
$days = mysql_result($raw, 0, 1);
Note that if there is more than one row that has the same day value (which satisfies all of the predicates), that day value is counted only once. If you want a count of rows that have a non-NULL day value, including any duplicates, then omit the DISTINCT keyword.)
Note that the SQL statement could be more simply written; you could omit the (unnecessary) inline view (i.e. derived table) and the unnecessary ORDER BY ...
SELECT SUM(p.hours) AS sum_hours
, COUNT(DISTINCT p.day) AS cnt_days
FROM payroll p
WHERE p.day BETWEEN '{$date1}' AND '{$date2}'
AND p.company = '{$latte}'
May be you can use DateTime::diff

How to output day of week from MySQL date

I'm having trouble finding or figuring out how to output a MySQL date field as the abbreviated day of week.
I'm not sure whether to do this in MySQL or PHP.
Ideally I'd like to do this with a PHP function, but to complicate things, the date field that I want to output as day of week is running through a while loop into a table. This makes me think I need to do it in MySQL.
Basically, I want to be able to use something like PHP's mktime() or MySQL's DAYOFWEEK(), except since I need to be able to do this in the while loop, I need to be able to use a variable or column name in the function instead of having to input or pull one specific date for formatting.
Any help is greatly appreciated!
P.S. I've added below how the data is currently coming from the database. The ### is where I'm having trouble; this is where I need to to echo the Day using the 'e_date' column. (The next Date also uses the 'e_date' column.)
// Get all the data from the "events" table
$result = mysql_query("
SELECT *
FROM events
WHERE e_type != '' && e_date >= CURDATE() && e_date <= (CURDATE() + 15)
ORDER BY e_date,e_ampm,e_time")
or die(mysql_error());
echo "<table border='1' style=\"border:none;font-size:12px;\">";
echo "<tr> <th>Day</th> <th>Date</th> <th>Time</th> <th>Type</th> <th>Description</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
###
echo "</td><td>";
echo $row['e_date'];
echo "</td><td>";
echo $row['e_time'];
echo $row['e_ampm'];
echo "</td><td>";
echo $row['e_type'];
echo "</td><td>";
echo $row['e_name'];
echo "</td></tr>";
}
echo "</table>";
Try this modified version. You can use DATE_FORMAT, use the datefield as the input variable, and %a signifies the formatting for the output. %a tells DATE_FORMAT to return the abbreviated day of the date. Give it a shot and see if it works, I haven't used MySQL in a while so I could be wrong.
// Get all the data from the "events" table
$result = mysql_query("
SELECT DATE_FORMAT(e_date, '%a') as day, e_date, e_time, e_ampm, e_type,e_name
FROM events
WHERE e_type != '' && e_date >= CURDATE() && e_date <= (CURDATE() + 15)
ORDER BY e_date,e_ampm,e_time")
or die(mysql_error());
echo "<table border='1' style=\"border:none;font-size:12px;\">";
echo "<tr> <th>Day</th> <th>Date</th> <th>Time</th> <th>Type</th> <th>Description</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['day'];
echo "</td><td>";
echo $row['e_date'];
echo "</td><td>";
echo $row['e_time'];
echo $row['e_ampm'];
echo "</td><td>";
echo $row['e_type'];
echo "</td><td>";
echo $row['e_name'];
echo "</td></tr>";
}
echo "</table>";
I would keep the database part to dealing with the data, and presentation to PHP. You want to use strftime() or strptime() depending how your data is coming out of MySQL.
My advice is always deal with date in unixtime format. I always store date as integer field in database.
For your case, you may query the datefield by converting it into unixtime and let php date function to handle the formating.
<?php
$query = "
SELECT UNIX_TIMESTAMP(e_date) AS UNIXTIME, *
FROM events
WHERE e_type != '' && e_date >= CURDATE() && e_date <= (CURDATE() + 15)
ORDER BY e_date,e_ampm,e_time";
$result = mysql_query($query) or die("error");
...
while($row = mysql_fetch_array( $result ))
{
echo "<tr>";
echo sprintf('<td>%s</td>', date('l', $row["UNIXTIME"])); //day of week
...
echo "</tr>";
}
?>

Categories