How to add due dates with CURRENT_TIMESTAMP? - php

I'm trying to make a library booking system so when user borrows a book, they will have a due date set 7 days after the issue date (set as CURRENT_TIMESTAMP). However, is there a way for me to just use the CURRENT_TIMESTAMP + 7 days in the php/html code? or do I need to add another table column to set the due date variable in the database?
I have tried to change a variable (fine) in the database which is not needed in my database with the due date. However, this messes up the whole thing which the data wont show.
So currently, I'm trying to add 7 days to the IssueDate variable via DATE_ADD function. However, this won't allow the code to show.
<tr>
<th>#</th>
<th>Book Name</th>
<th>ISBN </th>
<th>Issued Date</th>
<th>Due Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$sid=$_SESSION['stdid'];
$sql="SELECT tblbooks.BookName,tblbooks.ISBNNumber,tblissuedbookdetails.IssuesDate,tblissuedbookdetails.ReturnDate,tblissuedbookdetails.id as rid,tblissuedbookdetails.fine from tblissuedbookdetails join tblstudents on tblstudents.StudentId=tblissuedbookdetails.StudentId join tblbooks on tblbooks.id=tblissuedbookdetails.BookId where tblstudents.StudentId=:sid order by tblissuedbookdetails.id desc";
$query = $dbh -> prepare($sql);
$query-> bindParam(':sid', $sid, PDO::PARAM_STR);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $result)
{ ?>
<tr class="odd gradeX">
<td class="center"><?php echo htmlentities($cnt);?></td>
<td class="center"><?php echo htmlentities($result->BookName);?></td>
<td class="center"><?php echo htmlentities($result->ISBNNumber);?></td>
<td class="center"><?php echo htmlentities($result->IssuesDate);?></td>
<td class="center"><?php if($result->ReturnDate=="")
{?>
<span style="color:red">
<?php echo htmlentities("Not Return Yet"); ?>
</span>
<?php } else {
echo htmlentities($result->SELECT DATE_ADD(d,7,IssuesDate));
}
?></td>
<td class="center">
<a href="test-return.php?rid=<?php echo htmlentities($result->rid);?>">
<button class="btn btn-primary"><i class="fa fa-edit "></i>Extend</button>
</td>
</tr>
<?php $cnt=$cnt+1;}} ?>
</tbody>
Any "working codes" will not show the results in the "due date" table column and those that are not will just said there's unexpected variable, symbols, etc.

You need to caclculate 7 days in PHP rather than SQL. Use following code in your else block to calculate and display the Due Date.
$datetime = new DateTime( $result->IssuesDate );
$datetime->modify('+7 days');
echo $datetime->format('Y-m-d');

CURRENT_TIMESTAMP + 7 days
The correct syntax in standard SQL is:
CURRENT_TIMESTAMP + INTERVAL 7 DAY
(Your query is valid but does not do what you think it does.)
You possibly want to allow the complete day so you can drop time altogether by using CURRENT_DATE instead of CURRENT_TIMESTAMP:
SELECT CURRENT_DATE AS today, CURRENT_DATE + INTERVAL 7 DAY AS due_date;
+------------+------------+
| today | due_date |
+------------+------------+
| 2019-07-13 | 2019-07-20 |
+------------+------------+

Related

SQL How to order by differents times

Hi, I have created in the db two rows for one flight, one for the arrival and another for departure. Now Ineed to order by arrival time and departure time in the order.
This is my code but it's not working.
In the date that I've selected I have to display the arrivals and departures in the rights order eg:
Flight 1 : arr 10:30
Flight 2 : dep 10:55
Flight 1 : Dep 11:00
Flight 5 : Dep 11:20
And so on....
$sqlArr = "SELECT * FROM flights WHERE arr_date = '$date' OR dep_date = '$date' ORDER BY
eta,etd ASC";
$query = mysqli_query($cnx, $sqlArr);
foreach ($query as $key => $v ){
if ($v['xid_arrival'] == 0) {?>
<tr>
<td>ARR</td>
<td><?=$v['arr_date'];?> </td>
<td><?=$v['atyp'];?> </td>
<td><?= $v['reg'];?> </td>
<td><?=$v['arr_cls'];?> </td>
<td><?=$v['adep'];?> </td>
<td><?= date('H:i', strtotime($v['eta']));?> </td>
<td onclick="openRow(this, <?= $v['id_flt'];?>)">+</td>
</tr>
<tr hidden id="<?= $v['id_flt'];?>">
<td colspan="6">hidden id <?= $v['id_flt'];?></td>
</tr>
<?php } else { ?>
<tr>
<td>DEP</td>
<td><?=$v['dep_date'];?> </td>
<td><?=$v['atyp'];?> </td>
<td><?= $v['reg'];?> </td>
<td><?=$v['dep_cls'];?> </td>
<td><?=$v['ades'];?> </td>
<td><?= date('H:i', strtotime($v['etd']));?> </td>
<td onclick="openRow(this, <?= $v['xid_arrival'];?>)">+</td>
</tr>
<tr hidden id="<?= $v['xid_arrival'];?>">
<td colspan="6">hidden xid <?= $v['xid_arrival'];?></td>
</tr>
<?php }?>
<?php } ?>
You need to create one column with departure or arrival date depending which is defined in a line and order by that column.
Something like this
SELECT
*,
CASE
WHEN eta > 0 THEN eta
WHEN etd > 0 THEN etd
END as sort_order
FROM flights
WHERE
arr_date = '$date' OR dep_date = '$date'
ORDER BY
sort_order ASC;
And remember to escape data you get as input to your SQL query to prevent SQL injection vulnerabilities.
And SELECT * is lazy coding. Select only columns you neeed.

Display only specific data from array containing database values

I have a query which select the last entered data into the database month wise and i have assigned it into an array and tried to display it inside a table which works fine but the data is combined togeather as shown below
Example - the first numeric data you see on the table 1245871 should be displayed as follows
Month - 12
Closing Mileage - 45871
But as you can see on the image both the data are combined togeather how can i seperate these two values and display them accordingingly. The code for this is as below,
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$querymain = "SELECT * FROM users";
$resultsmain = mysqli_query($connect,$querymain);
if ($resultsmain->num_rows>0) {
while ($userid = mysqli_fetch_assoc($resultsmain)) {
?>
<table class="table" class="mt-3 mb-3">
<thead class="bg-dark text-light">
<tr>
<th colspan="3"><?php echo $userid['id']; ?></th>
<th colspan="3"><?php echo $userid['name']; ?></th>
<th colspan="3"><?php echo $userid['approved_kmpl'];?> KM</th>
</tr>
</thead>
<thead>
<tr>
<th>Month</th>
<th>Closing Mileage</th>
<th>Usage For Month</th>
<th>Required Per Month</th>
<th>Excess Used</th>
<th>(%)</th>
<th>KM/L</th>
<th>Consumed Liters</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
<?php
$closingmileage = "SELECT extract(MONTH from date) as Month,
MAX(mileage) FROM mileagesnew
WHERE user_id='".$userid['id']."'
AND extract(YEAR FROM date) ='2020'
group by Month
ORDER BY month desc";
$closingres = mysqli_query($connect,$closingmileage);
if ($closingres->num_rows>0) {
while ($closingrow = mysqli_fetch_assoc($closingres)) {
$data =array($closingrow);
foreach($data as $value){
print_r($value);
?>
<tr>
<td> <?php echo implode($value); ?> </td>
</tr>
<tr>
<td> <?php echo implode($value); ?> </td>
</tr>
<?php
}
}
}
else{
echo "No Data Found";
}
?>
</tbody>
</table>
<?php
}
}
You have 2 columns returned in the resultset of the query Month and mileagesnew. So $closingrow will be an array with 2 members, named as the columns names from your table, or the alias you give the column name in the query. So all you need to do is output $closingrow['Month'] and $closingrow['mileagesnew'] seperately in the 2 table cells
Also I assume you want the 2 values on the same row of the tabel to output both cells within the same <tr>...</tr> along with the empty cells you have not filled yet
<?php
$closingmileage = "SELECT extract(MONTH from date) as Month,
MAX(mileage) FROM mileagesnew
WHERE user_id='".$userid['id']."'
AND extract(YEAR FROM date) ='2020'
group by Month
ORDER BY month desc";
$closingres = mysqli_query($connect,$closingmileage);
if ($closingres->num_rows>0) {
while ($closingrow = mysqli_fetch_assoc($closingres)) {
echo "<tr>
<td>$closingrow[Month]}</td>
<td>$closingrow[mileagesnew ]</td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>";
}
} else{
echo "No Data Found";
}
?>

SQL pulling data based on date

I have a database full of store information and personal transactions. I have two webpages. One takes user input for the store name and runs a query pulling all transaction info for that store. I have another page almost identical that takes input for a start date and an end date and then runs a query for transactions between that date. The one for the store name works perfectly, but the one for the date doesn't display anything. I am still learning html/php/sql but I know exactly how the first page works so I cannot see why the same doesn't work for the second. If someone could help me, I'd appreciate it.
Here is my first page for the store name search that works.
<?php
$transaction = $_REQUEST["StoreName"];
require_once 'login.php';
$connection = mysqli_connect(
$db_hostname, $db_username,
$db_password, $db_database);
$sql = "SELECT * FROM PURCHASE WHERE StoreName LIKE '%".$transaction."%'";
$result = $connection->query($sql);
?>
Purchases Made From <?php echo $transaction ?>
<table border="2" style="width:100%">
<tr>
<th width="15%">Item Name</th>
<th width="15%">Item Price</th>
<th width="15%">Purchase Time</th>
<th width="15%">Purchase Date</th>
<th width="15%">Category</th>
<th width="15%">Rating</th>
</tr>
</table>
<?php
if($result->num_rows > 0){
// output data of each row
while($rows = $result->fetch_assoc()){ ?>
<table border="2" style="width:100%">
<tr>
<td width="15%"><?php echo $rows['ItemName']; ?></td>
<td width="15%"><?php echo $rows['ItemPrice']; ?></td>
<td width="15%"><?php echo $rows['PurchaseTime']; ?></td>
<td width="15%"><?php echo $rows['PurchaseDate']; ?></td>
<td width="15%"><?php echo $rows['PurchaseCategory']; ?></td>
<td width="15%"><?php echo $rows['Rating']; ?></td>
</tr>
<?php
}
}
?>
And here is the page for the date search that returns no data.
<?php
$startDate = $_REQUEST["StartDate"];
$endDate = $_REQUEST["EndDate"];
require_once 'login.php';
$connection = mysqli_connect(
$db_hostname, $db_username,
$db_password, $db_database);
$sql = "SELECT * FROM PURCHASE WHERE PurchaseDate BETWEEN '%".$startDate."%' and '%".$endDate."%'";
$result = $connection->query($sql);
?>
Purchases Made Between <?php echo $startDate ?> and <?php echo $endDate ?>
<table border="2" style="width:100%">
<tr>
<th width="15%">Item Name</th>
<th width="15%">Item Price</th>
<th width="15%">Purchase Time</th>
<th width="15%">Purchase Date</th>
<th width="15%">Category</th>
<th width="15%">Rating</th>
</tr>
</table>
<?php
if($result->num_rows > 0){
// output data of each row
while($rows = $result->fetch_assoc()){ ?>
<table border="2" style="width:100%">
<tr>
<td width="15%"><?php echo $rows['ItemName']; ?></td>
<td width="15%"><?php echo $rows['ItemPrice']; ?></td>
<td width="15%"><?php echo $rows['PurchaseTime']; ?></td>
<td width="15%"><?php echo $rows['PurchaseDate']; ?></td>
<td width="15%"><?php echo $rows['PurchaseCategory']; ?></td>
<td width="15%"><?php echo $rows['Rating']; ?></td>
</tr>
<?php
}
}
?>
Obviously the initial search pages that link to both of these output pages differ a bit more but I can confirm that the date output page is receiving the correct dates from the search page.
EDIT: Here is the search page for the date.
<!DOCTYPE html>
<html>
<head>
<title>Output 2</title>
</head>
<body>
<h1>Required Output 2</h1>
<h2>Transaction Search By Date</h2>
<br/>
<br/>
<form action="outputout2.php" method="get">
Start Date: <input type="date" name="StartDate">
End Date: <input type="date" name="EndDate">
<input name="Add Merchant" type="submit" value="Search">
</form>;
</body>
</html>
This sort of problem is usually the result of misformatted dates.
Your query, if I'm reading it right, says this when you've finished assembling it in php and sent it to the SQL server:
SELECT *
FROM PURCHASE --wrong!
WHERE PurchaseDate BETWEEN '%5/1/2016%' and '%5/8/2016%'
This is not going to work.
For one thing, the % signs only work with the LIKE operator, not on equality and inequality operators.
For another thing, different makes and models of database server software use differently formatted date strings. MySQL and SQL Server will work fine with string formats like 2016-05-01. But you have to look up the appropriate ways of doing this for the kind of SQL software product you are using. This kind of stuff is not very vendor-portable.
Third: your PurchaseDate column in your table needs to have a date-like datatype for this kind of thing to work.
Fourth: if your PurchaseDate items are timestamps -- that is, if that have both dates and times -- you can't reliably use the BETWEEN operator. Here's why: Suppose you have a value of 2016-05-08 11:50:00 When you compare that to an end date 2016-05-08, it lies beyond the end date. So, what you really need is this:
WHERE PurchaseDate >= '2016-05-01'
AND PurchaseDate < '2016-05-09' -- the day AFTER your end date
That construct performs the same as BETWEEN and doesn't screw up the last days' data.
Edit so it's MySQL you're using.
Workbench is a client program. So is PHP. The server is MySQL. When you do an operation like
DateColumn < 'string constant'
MySQL implicitly converts the string constant to a date. If the format of the string constant is close enough to ISO 8601 for the server to figure out what it means, it will convert it. 2016-12-13 is exactly right. 2016-5-31 is close enough for MySQL, and so is 2016-5-5. 2016/12/31 doesn't work. Neither does 5/5/16.
Germane to your question is this: MySQL cannot convert %2016-5-5% (with the percent signs) to a date.
When MySQL can't convert a date, it comes up with NULL. Comparisons with NULL values are weird. And, in the immortal words of Hunter S. Thompson, "when the going gets weird, the weird turn pro". NULL weirdness is probably the root cause of your empty result set in the query you showed.

How to send each client ID data from Database to each different email

I m struggling to send Each ClientID Information from Database to their specific Email Address.
My training exercise was to use this SQL (See Below) that have 3 different tables that are as follow: Client, Sites, Job_Cards.
Now I have create a SQL that gives me the output that I need. But my problem is based at the fact that 1 clientID may have one or Many SiteID. one SiteID may have one and many Job_Card#.
When I create my PHP Script the Data Displays as follow: Link on a HTML page.
My Question is in 2 Parts:
How can I format the table to Display ONLY 1 ClientID or ClientName with the list of Job#, site name and Description of this single Client?
How may I send an Email to Each of the ClientName Without Duplicate ID. And What php script will be good to use to send Emails to Each Clients?
Here is my PHP Script and My SQL Statment:
$sqlSelect = "SELECT DISTINCT(cl.client_id),
client_name,
DATE(jb.date),
jb.job_number,
jb.repair,
st.site_name
FROM
job_cards jb
INNER JOIN
clients cl ON (cl.client_id = jb.client_id)
LEFT JOIN
sites st on (st.site_id = jb.site_id)
WHERE
jb.completed = 1
AND cl.client_id = jb.client_id
AND jb.date >= DATE_ADD(DATE(NOW()), INTERVAL - 30 DAY)
ORDER BY cl.client_name ASC";
//echo $sqlSelect;
$tresult = mysql_query($sqlSelect);
//die("ss");
//$dataCount = mysql_num_rows($result);
while($userData = mysql_fetch_assoc($tresult)){
if($i%2==0)
$classname = 'evenRow';
else if($i%2==1)
//extract($userData);
?>
</table>
</td>
</tr>
<tr>
<td align='center' height="30" style="font-size:14px;">
<b><?php echo $userData['client_name'];?></b>
</td>
<td align='center'></td>
<td>
<table width='100%' cellpadding= '1' border='0'>
<thead>
<tr>
<td style="font-size:13px; text-align:Left;"><b>Date</b></td>
<td style="font-size:13px; text-align:Left;"><b>Job #</b></td>
<td style="font-size:13px; text-align:left;"><b>Site name</b></td>
<td style="font-size:13px; text-align:left;"><b>Description</b></td>
</tr>
</thead>
<tr class='<?php if(isset($classname)) echo $classname;?>'>
<tr>
<td>
<?php echo mysql_real_escape_string ($userData['DATE(jb.date)']); ?>
</td>
<td>
<?php echo mysql_real_escape_string($userData['job_number']);?>
</td>
<td>
<?php echo mysql_real_escape_string($userData['site_name']);?>
</td>
<td>
<?php echo mysql_real_escape_string($userData['repair']);?>
</td>
</tr>
<?php $i++;
}
?>
</tr>
</table>
<table width='100%' cellpadding= '1' border='1'>
<tr>
</tr>
</table>
Please May Some 1 Help me. I tried What I could But Still I cannot send emails and the Table format doesn't display the way I want.
Thank.

Mysql loop through database based on timestamp?

In my database I store orders as entryDate based on Unix timestamp. I would like to make a simple HTML chart that displays the number of orders of a given day. But this is thougher that it sounds (for me atleast).
How do I loop through my database based on an unix timestamp? How do I then get the total number of orders of that day? The furtest I got is:
SELECT COUNT(id)
FROM customers_orders
WHERE entryDate >= NOW() - INTERVAL 7 DAY
AND status != 99 AND totalprice > 0 AND importId = 0
For orders of TODAY I use:
SELECT COUNT(id) FROM customers_orders WHERE DATE_FORMAT(FROM_UNIXTIME(`entryDate`), '%Y-%m-%d') = CURDATE() AND status != 99
The end result should be something simple like:
<table>
<tr>
<td><?= $objStats->numMonday; ?></td>
<td>Monday</td>
</tr>
<tr>
<td><?= $objStats->numTuesday; ?></td>
<td>Tuesday</td>
</tr>
<tr>
<td><?= $objStats->numWednesday; ?></td>
<td>Wednesday</td>
</tr>
<tr>
<td><?= $objStats->numThursday; ?></td>
<td>Thursday</td>
</tr>
<tr>
<td><?= $objStats->numFriday; ?></td>
<td>Friday</td>
</tr>
<tr>
<td><?= $objStats->numSaturday; ?></td>
<td>Saturday</td>
</tr>
<tr>
<td><?= $objStats->numSunday; ?></td>
<td>Sunday</td>
</tr>
</table>
DATE(entryDate) gives you the YYYY MM DD part of your timestamp, group your query with that.
SELECT COUNT(id), DATE(entryDate)
FROM customers_orders
WHERE entryDate >= NOW() - INTERVAL 7 DAY
AND status != 99 AND totalprice > 0 AND importId = 0
GROUP BY DATE(entryDate)

Categories