SQL / PHP display only upcoming events - php

Hope everyone is awesome. What is the best way to display only future events in an event list which is generated by PHP and SQL.
function select_events($sql) {
include 'connect.php';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table id='event-list'>\n
<tr>\n
<th id='event'>Event</th>\n
<th id='date-of-event'>Date</th>\n
<th id='time'>Time</th>\n
<th id='place'>Place</th>\n
<th id='admission'>Admission</th>\n
</tr>";
}
while ($row = $result->fetch_assoc()) {
$date = new DateTime($row['date']);
$formatted_date = $date->format('d/m/Y');
$time = new DateTime($row['time']);
$formatted_time = $time->format('HH:MM');
echo "<tr>\n
<td id='event'>".$row['event']."</td>\n
<td id='date-of-event'>".$formatted_date."</td>\n
<td id='time'>".$row['time']."</td>\n
<td id='place'>".$row['place']."</td>\n
<td id='admission'>".$row['admissions']."</td>\n
</tr>\n";
}
echo "</table>\n";
}
<?php select_events("SElECT * FROM events ORDER BY date, time"); ?>
Thanks everyone in advance. :)

try this,
<?php select_events("SElECT * FROM events WHERE `date` >= CURDATE() ORDER BY `date`, `time`"); ?>
use backticks for mysql reserved keywords

You need to add a condition to check for date and also for time.
Check whether date is greater than today and time is greater than current time.
<?php select_events("SElECT * FROM events WHERE `date` >= " . date('Y-m-d') . " AND `time` > " . date('H:i:s') . " ORDER BY `date`, time"); ?>

Related

Filter data from database on datetimepicker input uisng MySQL, PHP and PDO

I'm trying to do search base on the input in two datetimepicker and display the results into table, but when I pick specific date rage all data are displaying. I'm using MySQL and PDO.
Here is my code.
<?php
$date1 = date("Y-m-d", strtotime($_POST['date1']));
$date2 = date("Y-m-d", strtotime($_POST['date2']));
$db = new PDO('mysql:host=localhost;dbname=db_search;charset=utf8mb4',
'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = "select * from book";
$stmt = $db->prepare($sql);
$stmt->execute();
$row_count = $stmt->rowCount();
if($row_count > 0){
while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
?>
<tr>
<td><?php echo $row['ISBN']?></td>
<td><?php echo $row['title']?></td>
<td><?php echo $row['author']?></td>
<td><?php echo date("m/d/Y", strtotime($row['date_published']))?></td>
</tr>
<?php
}
}else{
echo '
<tr>
<td colspan = "4"><center>Record Not Found</center></td>
</tr>
';
}
?>
You haven't actually included the date conditions in your query, which is why it is still returning all the data. Change your query to
$sql = "select * from book where date_published between '" . min($date1, $date2) . "' and '" . max($date1, $date2) . "'";
If you know that $date1 is less than $date2, you can simplify that to
$sql = "select * from book where date_published between '$date1' and '$date2'";
Note that your code is wide open to SQL Injection, you should really use prepared statements. See this question for more info...

Display sum of timestamps as 00:01:26 instead of 126

I'm working on a site where workers' hours are calculated based on when they clock in (start) and clock out (end). end - start = total. I have successfully computed the difference between the start and end. The start, end, and total are inserted into a DB. The "Shift total" comes from the SQL SUM of total in the db. The last foreach statement is the code in question. I want to format the "Shift total" as 00:00:00 so that it would show as 00:01:26 instead of 126. I have tried ". $row['SUM(total)'] + '00:00:00' . " but it didn't work. Any suggestions on how I should go about this? Thanks in advance. I pasted the results first then the code.
____start____________end____________total
10:44:46 AM 10:44:49 AM 00:00:03
10:50:12 AM 10:50:14 AM 00:00:02
10:50:27 AM 10:50:32 AM 00:00:05
11:12:02 AM 11:13:18 AM 00:01:16
Shift total --> 126
$sql3 = "SELECT date, startTime, endTime, total FROM timeSheet WHERE userName='$user_name'";
$sql4 = "SELECT SUM(total) FROM timeSheet WHERE userName='$user_name'";
echo "<table border='1'>
<tr>
<th>date</th>
<th>start</th>
<th>end</th>
<th>total</th>
</tr>";
foreach ($conn->query($sql3) as $row) {
$start = explode (" ", $row['startTime']);
$end = explode(" ", $row['endTime']);
if ($start[1] == '00:00:00'){
$start[1] = '0';
}else if ($end[1] == '00:00:00'){
$end[1] = '0';
}else{
$start[1] = date("h:i:s A", strtotime($start[1]));
$end[1] = date("h:i:s A", strtotime($end[1]));
}
echo "<tr>
<th>" . $row['date'] . "</th>
<th>" . $start[1] . "</th>
<th>" . $end[1] . "</th>
<th>" . $row['total'] . "</th>
</tr>";
}
foreach ($conn->query($sql4) as $row) {
echo "<tr>
<th></th>
<th></th>
<th>SUM</th>
<th>". $row['SUM(total)'] . "</th>
</tr>";
}
echo "</table>";
you can do it with the TIME function:
$sql4 = "SELECT TIME(SUM(total)) AS totalSum FROM timeSheet WHERE userName='$user_name'";
//....
foreach ($conn->query($sql4) as $row) {
echo "<tr>
<th></th>
<th></th>
<th>SUM</th>
<th>". $row['totalSum'] . "</th>
</tr>";
}
hint:
actually you don't need the total column in your database. You can use i.e
SELECT date, startTime, endTime, TIMEDIFF(startTime, endTime) AS total FROM timeSheet WHERE userName='$user_name'"
and
SELECT TIME(SUM(TIMEDIFF(startTime, endTime))) AS totalSum FROM timeSheet WHERE userName='$user_name'
for further information have a look at: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timediff

PHP MYSQL Chained Drop down How to DISPLAY data

<?php require_once('../includes/header.php');?>
<?php require_once('../includes/connection.php');?>
<?php include('../includes/get_username.php');?>
<?php
include('sanitise.php');
$month = sanitise($_GET['month']);
?>
<table id="contentbox">
<tr>
<td>
<?php
$color="1";
//view record
$qry = mysql_query("SELECT * FROM tbl_dv WHERE monthname(date_added) = '$month' ORDER BY dv_id DESC");
echo "<table class='dvr_table' id='alternatecolor' width='100%'>
<tr>
<th>DATE ADDED</th>
<th>CT</th>
<th>PAYEE</th>
<th>PARTICULAR</th>
<th>PM</th>
<th>VOUCHER NO.</th>
<th>NET</th>
<th>OBR NO.</th>
<th>";
//RESPO/Office
$sql = "SELECT respo FROM tbl_dv WHERE monthname(date_added) = '$month' GROUP BY respo";
$result = mysql_query($sql);
echo "<select name='respo'>
<option value=' ' disabled='disabled' selected='selected'>Select a RESPO/Office</option>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['respo'] . "'>" . $row['respo'] . "</option>";
}
echo "</th>
<th>ACCOUNT CODE</th>
<th>FPP CODE</th>
<th>DEDUCTION</th>
</tr>";
while ($row = mysql_fetch_array($qry)) {
$dv_id = $row['dv_id'];
if($color==1){
echo "<tr bgcolor='#ffffff'>
<td style='text-align:center;'>" .date_format(date_create($row['date_added']), 'm/d/y')." </td>
<td style='text-align:center;'>" .$row['cashtype']."</td>
etc.......
$color="2";
} else {
echo "<tr bgcolor='#ebeaea'>
<td style='text-align:center;'>" .date_format(date_create($row['date_added']), 'm/d/y')." </td>
<td style='text-align:center;'>" .$row['cashtype']."</td>
etc......
$color="1";
}
}
echo "</tr>";
?>
I Have all it work. Only 1 PROBLEM.. I CANNOT DISPLAY the selected RESPO/OFFICE. As I select the RESPO/OFFICE it will sort out the selected RESPO/OFFICE... What should I resvise my code or add code.. Please Help!
A few suggestions first:
mysql is depreciated and you should move to PDO prepared statements
or mysqli. You can consult the php manual for this.
comment your code, you are not able to follow along unless you read
from top to bottom.
Now onto your code:
<?php
// Start document with includes needed, header, connection, functions.
require_once('../includes/header.php');
require_once('../includes/connection.php');
include('../includes/get_username.php');
include('sanitise.php');
// Start with the month variable posted from $_GET, this will begin the initial display.
$month = sanitise($_GET['month']);
?>
<!-- Begin Table Display and Layout -->
<table id="contentbox">
<tr>
<td>
<?php // Open PHP Tag to get variables to display in the table
$color="1";
// Initial Query to get the data for the month passed by GET, ordering by dv_id.
$qry = mysql_query("SELECT * FROM tbl_dv WHERE monthname(date_added) = '$month' ORDER BY dv_id DESC");
// Format the table rows for display
echo "<table class='dvr_table' id='alternatecolor' width='100%'>
<tr>
<th>DATE ADDED</th>
<th>CT</th>
<th>PAYEE</th>
<th>PARTICULAR</th>
<th>PM</th>
<th>VOUCHER NO.</th>
<th>NET</th>
<th>OBR NO.</th>
<th>";
// Fill the SELECT option with all the RESPO/Office data
$sql = "SELECT respo FROM tbl_dv WHERE monthname(date_added) = '$month' GROUP BY respo";
$result = mysql_query($sql);
// Display the select with the newly populated content
echo "<select name='respo'>
<option value=' ' disabled='disabled' selected='selected'>Select a RESPO/Office</option>";
// While the result contains data we will display respo as a select option.
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['respo'] . "'>" . $row['respo'] . "</option>";
}
// Finish the table header
echo "</th>
<th>ACCOUNT CODE</th>
<th>FPP CODE</th>
<th>DEDUCTION</th>
</tr>";
// While we have data from the original query we will display it
while ($row = mysql_fetch_array($qry)) {
$dv_id = $row['dv_id']; // grab the dv_id
if($color==1){ // Setup color scheme
echo "<tr bgcolor='#ffffff'> // Color for the row
// Let's begin filling the table with data
<td style='text-align:center;'>" .date_format(date_create($row['date_added']), 'm/d/y')." </td>
<td style='text-align:center;'>" .$row['cashtype']."</td>
etc.......
$color="2";
} else {
echo "<tr bgcolor='#ebeaea'>
<td style='text-align:center;'>" .date_format(date_create($row['date_added']), 'm/d/y')." </td>
<td style='text-align:center;'>" .$row['cashtype']."</td>
etc......
$color="1";
}
}
echo "</tr>";
?>
After reviewing the above code it is clear that you haven't setup a query to filter the data that you are displaying based on the selected option.
Your first query:
// Initial Query to get the data for the month passed by GET, ordering by dv_id.
$qry = mysql_query("SELECT * FROM tbl_dv WHERE monthname(date_added) = '$month' ORDER BY dv_id DESC");
You could append a new variable for the selected option, expand your WHERE statement. WHERE monthname(date_added) = '$month' && respo = '$respo' and move this query after the select option so it has access to the value chosen by the select option. Lastly, unless you are going to use jQuery to deal with the select box changing values, you would need a submit button to show the state change for the select option.
Pseudo Code:
Check for Submit
Change value of the department in the query WHERE clause
Display the requested data
This should get you in the direction you need to go in order to achieve the desired result.
EDIT:
In the 3rd answer you posted:
$viewrecord = "SELECT * FROM tbl_dv WHERE respo='".mysql_real_escape_string($respo)."' AND year(date_added)='$year' GROUP BY date_added ";
You said it is not filtering by the month being passed in, you are not adding it into your query, specifically the WHERE clause. So it should be:
$viewrecord = "SELECT * FROM tbl_dv WHERE respo='".mysql_real_escape_string($respo)."' AND month(month_added)='$month' AND year(date_added)='$year' GROUP BY date_added ";
FINAL EDIT:
Your first issue stems from not sending the $_GET['date_added'] value to the view page, so you will never display anything. Properly format the select box and add the data for the RESP and Date data from the database:
echo "<option value='". $row['respo'] . "+". $row['date_added'] . "'>" . $row['respo'] . " (".$row['count(*)'].")</option>";
Now that we are passing the respo and the date string we can work with the data on the next page:
/* UNCOMMENT NEXT LINE FOR ERROR DETECTION */
//error_reporting( E_ALL );
/* GET THE ENTIRE STRING PASSED FROM THE SELECT OPTION */
$respo = $_GET['respo'];
/* EXPLODE THE DATA BY + SYMBOL TO GET THE DATA */
$data = explode("+", $respo);
/* FORMAT THE DATETIME FROM THE STRING TO A FRIENDLY FORMAT */
$month = date("m", strtotime($data[1])) . "<br />";
$year = date("Y", strtotime($data[1])) . "<br />";
This is how I choose to work with the data and get what I needed, so now the query would be:
$viewrecord = "SELECT * FROM tbl_dv WHERE respo='".mysql_real_escape_string($data[0])."' && year(date_added)='$year' && month(date_added)='$month' ";
This will only display the records for the RESPO and the date by year and month passed into the page via $_GET.
<?php require_once('../includes/header.php');?>
<?php
$respo = $_GET['respo'];
$month = (int) (!empty($_GET['date_added']) ? $_GET['date_added'] : date('m'));
$year = (int) (!empty($_GET['date_added']) ? $_GET['date_added'] : date('Y'));
//database call here
$viewrecord = "SELECT * FROM tbl_dv WHERE respo='".mysql_real_escape_string($respo)."' AND year(date_added)='$year' GROUP BY date_added ";
$result = mysql_query($viewrecord, $db) or die (mysql_error());
$num_result = mysql_num_rows($result);
{
echo "<table border='1' width='100%' style='border:1px solid silver' cellpadding='5px' cellspacing='0px'>
<tr bgcolor='#666666' style='color:#FFFFFF'>
<th>Date Encoded</th>
etc...... (header here)
while ($row = mysql_fetch_row($result)) {
echo '<tr>';
echo "<tr ><td align='center'>" .date_format(date_create($row[17]), "m/d/y")."</td>
etc...
}
mysql_close($db);
?>
This is the code i come up. This is just an alternative solution. But the problem with this solution is that. I won't display the record in MONTH as call. THe respo is working as I select the RESPO it will display the all RESPO I ask, but the problem is that it include all the previous months with the RESPO I select. When I just select the specific month only..
//RESPO/Office
**echo '<form action="view.php" method="post">';**
$byrespo = mysql_query("SELECT DISTINCT count(*), respo FROM tbl_dv WHERE monthname(date_added)='$month' GROUP BY respo");
echo "<select name='respo' onchange='this.form.submit()'>
<option value=' ' disabled='disabled' selected='selected'>Select a RESPO/Office</option>";
while ($row = mysql_fetch_array($byrespo)) {
echo "<option value='" . $row['respo'] . "'>" . $row['respo'] . " (".$row['count(*)'].")</option>";
}
echo "</select></form>";
I just rushing to came up with solution.. So I add a and I create another view.php

PHP using SELECT SUM

I am new to PHP, and was wondering if you could help with my select sum query?
I am wanting to add the total amount from my expenses table in my database based on user_id?
Here is what I have so far
<?php
//sets up thisPage
$pageSize=10;
if (isset($_POST["thisPage"]))
$thisPage = $_POST["thisPage"];
else
$thisPage=1;
//selects all distinct expenses that have been uploaded
$dbQuery="SELECT SUM(amount) AS TotalExpenditure FROM expenses WHERE user_id = '$userID'; ";
echo $dbQuery;
$dbResult=mysqli_query($db_connection, $dbQuery) or die (mysqli_error($db_connection));
echo "<table> <thead>";
//echo '<tr> <th>Project ID</th><th>Project Name</th></tr> </thead>';
while ($dbRow=mysqli_fetch_array($dbResult)){
// display row with expense
echo '<tr> <td>'. $dbRow['amount'] .'</td>';
}
echo "</table>";
echo "</form>";
?>
You have
$dbRow['amount']
but you use
SUM(amount) AS TotalExpenditure
// ^ this is the name (alias) of your column now
TotalExpenditure is the name of the amount, so the last part should be
echo '<tr> <td>'. $dbRow['TotalExpenditure'] .'</td> </tr>';
You have to use TotalExpenditure as key of your array, so
$dbRow['TotalExpenditure'] instead of $dbRow['TotalExpenditure']?
You're giving an alias to your count() sql function so you have to use it

Selecting row information by date

I'm trying to display data starting at a certain time and day and ending and another time and day. here is my code:
<?php
include 'includes/connect3.php';
$query = "SELECT * FROM u_visits WHERE date >= '2013-08-31 22:56:20' AND date <= '2013-
08- 31 23:59:59'";
$result = mysqli_query($con,$query);
echo "<table><tr>
<th>USER ID</th>
<th>TIMES VISITED</th>
</tr>";
while($row = mysqli_fetch_assoc($result))
{
echo "<tr><td>" . $row['id'] . "</td><td>" . $row['visits'] . "</td></tr>";
}
echo "</table>";
?>
When I go to the page, only the table header is displayed with no data showing.
you can also use BETWEEN for range comparisons.
$query = "SELECT * FROM u_visits WHERE `date` BETWEEN '2013-08-31 22:56:20' AND '2013-08-31 23:59:59'";
The reason you didn't see any result is because your query has some errors. The error in your query is that you have a space after 2013-08- in your where clause (date <= '2013-08- 31 23:59:59'";)
Had you used proper error handling, you would have noticed this yourself. One common way to do this is:
$result = mysqli_query($con,$query) or die ('Query execution failed: ' . mysqli_error($con));

Categories