only list jobs if current time > expiry time (php mysqli) - php

I am trying to list out all records from a database that have not expired.
i have a jobs listing site being developed, i have code to grab all the 'active' job details from the database and list out.
$mysql = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was a problem connecting to the database');
$stmtJ = $mysql->prepare('SELECT id,jobtitle,vcref,jobtype,jobintro,closingdate FROM jobs WHERE active = 1');
$stmtJ->execute();
$stmtJ->store_result();
$stmtJ->bind_result($id,$jobtitle,$vcref,$jobtype,$jobintro,$closingdate);
$totalLiveJobs = $stmtJ->num_rows();
and is outputted like so:
<?php
while($row = $stmtJ->fetch()) :
echo("<p>job detail here</p>");
endwhile;
?>
and i also have an 'if statement' snippet to see if the job has expired or not (i.e if expires {expires is a date yyyy-mm-dd} is greater than '$now' it should not show up.
$expires = date('Y-m-d-H-i-s',strtotime("$closingdate 12:00:00"));
$now = date('Y-m-d-H-i-s');
if ($expires < $now) {
echo ("<h3>Live Jobs Here</h3> $expires");
} else {
echo ("<h3>Job Expired</h3> $now");
}
However, i'm having problems merging the two together with the main goal being all jobs that have not yet expired will be shown on the page, any jobs that have expired should not be shown on the page.
I am pulling my hair out here, any help welcome, any requests for further details i'll respond as soon as i possibly can.
thx in advance

depending on your database structure, you could do
SELECT * FROM jobs WHERE active = 1 AND closingdate >= NOW()

You can merge two SQL query results together that have the same returned columns using UNION.
See more here: W3C Schools: SQL Union.

If all data stored within one table you can use this query:
SELECT id,jobtitle,vcref,jobtype,jobintro,closingdate
FROM jobs
WHERE CONCAT(closingdate, ' 12:00:00') > '{$mysql_timestamp}' AND active = 1
Note: mysql timestamp format is
date('Y-m-d H-i-s')
also you can use built in NOW() function, however depending on your hosting location there might be different timezone from your website audience.

Related

Check if the time is more than 24h and show it

I have in my MSSQL database a column with datatype of datetime which contains some dates in this format 2021-01-11 19:58:04.277.
This is a voting system, the idea is that the users can only vote once every 24 hours.
Every time they vote this table is updated with a new record and a new date is added with the corresponding user.
I want to display a message that says how many hours left to place the next vote.
This is the code I am trying to use:
/**
* Get Votes Time
*
*/
public function getVoteRemainingTime($account) {
date_default_timezone_get();
$currentTime = date('Y-m-d H:i:s');
$sql = "SELECT VoteDate FROM dbo.vote WHERE Account = :account ORDER BY logid DESC";
$query = $this->db->prepare($sql);
$query->execute(array(':account' => $account));
$voteDate = $query->fetch(PDO::FETCH_OBJ);
$timeLeftVote = strtotime($currentTime) - strtotime($voteDate->VoteDate);
if($timeLeftVote > 86400) {
return '<strong>Vote Available!</strong>';
} else {
return $timeLeftVote;
}
}
But it is displaying the wrong information. What I am doing wrong? I would appreciate your help.
Thanks!
you need declare format parameter of the date() like date('Y-m-d H:i:s')
date_default_timezone_get();
$currentTime = date('Y-m-d H:i:s');
$timeLeftVote = strtotime($currentTime) - strtotime('2021-01-11 19:58:04.277');
if($timeLeftVote > 86400){
echo 'Vote available';
}else{
echo $timeLeftVote;
}
Instead of SELECT VoteDate FROM dbo.vote
Can you do the calculation on the time difference at source in the database using
SELECT VoteDate, DATEDIFF(HOUR, VoteDate, GETDATE()) as HourDifference from dbo.vote
As I cannot check your database query, I only checked the rest of the code and it seems to work (as Fikri F mentioned in the comments of this post) if I replace $voteDate->VoteDate by a static date.
So please provide more information. You could output the current time and the previous vote time from the database as strings, and for both dates as well the result of strtotime, and in the end the result of the method. Then please explain, what the wrong behaviour is. By this, we can narrow down the problem either to the DB query or to the PHP code.
(I would write this as a comment, but I have not enough reputation.)

Time Calculations with MySQL

I'm writing a time logging programme for a client who is a piano tuner, and I've written the following PHP code to give a record a status of 'to do':
$last_tuned = '2017-01-05';
$tuning_period = 3;
$month_last_tuned = date('Y-m', strtotime(date('Y-m-d', strtotime($last_tuned))));
$next_tuning = date('Y-m', strtotime($month_last_tuned.(' +'.$tuning_period.' months')));
if (time() > strtotime($next_tuning.' -1 months')) {
if (time() > strtotime($next_tuning)) {
return 'late';
} else {
return 'upcoming';
}
}
As you can see, the $last_tuned variable is of the date(YYYY-MM-DD) format. This is then converted to a (YYYY-MM) format.
Once convered, an additional number of months, identical to $tuning_period is then added to the $month_last_tuned variable giving us a month and year value for when we need to add a new record.
If the current time (found with time()) is greater than the $next_tuning variable - 1 month, it returns that the task is upcoming. If it's after the $next_tuning variable, it returns that the task is late.
I now have to write a MySQL query to list the items that would return as upcoming or late.
How would I write this in MySQL? I'm not very good with MySQL functions, and some help would be much appreciated.
My attempt at the logic is:
SELECT * FROM records
// The next lines are to get the most recent month_last_tuned value and add the tuning_period variable
WHERE
NOW() > (SELECT tuning_date FROM tunings ORDER BY tuning_date ASC LIMIT 1)
+
(SELECT tuning_period FROM records WHERE records.id = INITIAL CUSTOMER ID)
I know that that is completely wrong. The logic is pretty much there though.
My database schema is as follows:
I expect the rows returned from the query to be on-par with the 'late' or 'upcoming' values in the PHP Code above. This means that the rows returned will be within 1 months of their next tuning date (calculated from last tuning plus tuning period).
Thanks!
You'd probably be better off with using the DateTime object instead of manipulating date strings.
$last_tuned = '2017-01-05';
$tuning_period = 3; // months
$dt_last_tuned = DateTimeImmutable::createFromFormat('Y-m-d',$last_tuned);
$dt_next_tuning = $dt_last_tuned->add(new DateInterval('P3M'));
$dt_now = new DateTimeImmutable();
$dt_tuning_upcoming = $dt_next_tuning->sub(new DateInterval('P1M'));
if( $dt_now > $dt_next_tuning) {
return 'late';
}
if( $dt_now > $dt_tuning_upcoming) {
return 'upcoming';
}
You can also use these DateTime objects in your MySQL queries, by building the query and passing through something like $dt_next_tuning->format('Y-m-d H:i:s'); as needed.
Given your table structure, however, it may be easier to just get all the relevant records and process them. It's a little difficult to tell exactly how the pieces fit together, but generally speaking MySQL shouldn't be used for "processing" stuff.

How to transform a PHP loop to a MySQL query?

I am trying to make a PHP loop work for me in MySQL. Currently all visits to a website via a specific URL parameterare logged into a table along with the date and time of the visit. I am rebuilding the logging procedure to only count the visits via one specific parameter on one day, but I'll have to convert the old data first.
So here's what I'm trying to do: The MySQL table (let's call it my_visits) has 3 columns: parameter, visit_id and time.
In my PHP code, I've created the following loop to gather the data I need (all visits made via one paramter on one day, for all parameters):
foreach (range(2008, 2014) as $year) {
$visit_data = array();
$date_ts = strtotime($year . '-01-01');
while ($date_ts <= strtotime($year . '-12-31')) {
$date = date('Y-m-d', $date_ts);
$date_ts += 86400;
// count visit data
$sql = 'SELECT parameter, COUNT(parameter) AS total ' .
'FROM my_visits ' .
'WHERE time BETWEEN \''.$date.' 00:00\' AND \''.$date.' 23:59\' '.
'GROUP BY parameter ORDER BY total DESC';
$stmt = $db->prepare($sql);
$stmt->execute(array($date));
while ($row = $stmt->fetch()) {
$visit_data[] = array(
'param' => $row['parameter'],
'visit_count' => $row['total'],
'date' => $date);
}
$stmt->closeCursor();
}
}
Later on, the gathered data is inserted into a new table (basically eliminating visit_id) using a multiple INSERT (thanks to SO! :)).
The above code works, but due to the size of the table (roughly 3.4 million rows) it is very slow. Using 7 * 365 SQL queries just to gather the data seems just wrong to me and I fear the impact of just running the script will slow everything down substantially.
Is there a way to make this loop work in MySQL, like an equivalent query or something (on a yearly basis perhaps)? I've already tried a solution using GROUP BY, but since this eliminates either the specific dates or the parameters, I can't get it to work.
You can GROUP further.
SELECT `parameter`, COUNT(`parameter`) AS `total`, DATE(`time`) AS `date`
FROM `my_visits`
GROUP BY `parameter`, DATE(`time`)
You can then execute it once (instead of in a loop) and use $row['date'] instead of $date.
This also means you don't have to update your code when we reach 2015 ;)

PHP and SQL getting latest entry in DB from DateTime

I have a database which id,title,subject and datetime and I'm calling a php page that takes in a request from clients to show the latest entry in the db from the difference of time from the client and checks with the last entry's datetime. PHP code as follows
$date = "2012-10-06 18:13:52";
//Establish a connection
$conn = mysql_connect('localhost','regadmin','regadmin');
//Select the mySQL db
$db = mysql_select_db('easy_comm', $conn);
$sql = mysql_query("SELECT `title`, `subject`,`date_sent` FROM `books` WHERE `date_sent` > '$date'", $conn);
$count=mysql_num_rows($sql);
if($count != 0){
$json = array('boolean' => true);
}
else{
$json = array('boolean' => false);
//echo "No record";
}
From the above code and the provided $date variable, it will always return true and the last entry is
2012-10-06 18:10:52
I have tried converting to UNIXTIMESTAMP but same problem
Well this works good enough for me.Please make sure the column against which you are comparing the date surely happens to be DATETIME column not a VARCHAR or something else.
Please post us database structure to see the collation as well and also try printing the query on the fly and then execute in your console.

PHP: mysql_fetch_array() in a while-loop takes too long

I am creating an online calendar for a client using PHP/MySQL.
I initiated a <table> and <tr>, and after that have a while loop that creates a new <td> for each day, up to the max number of days in the month.
The line after the <td>, PHP searches a MySQL database for any events that occur on that day by comparing the value of $i (the counter) to the value of the formatted Unix timestamp within that row of the database. In order to increment the internal row counter ONLY when a match is made, I have made another while loop that fetches a new array for the result. It is significantly slowing down loading time.
Here's the code, shortened so you don't have to read the unnecessary stuff:
$qry = "SELECT * FROM events WHERE author=\"$author\"";
$result = mysql_query($qry) or die(mysql_error());
$row = mysql_fetch_array($result);
for ($i = 1; $i <= $max_days; $i++) {
echo "<td class=\"day\">";
$rowunixdate_number = date("j", $row['unixdate']);
if ($rowunixdate_number == $i) {
while ($rowunixdate_number == $i) {
$rowtitle = $row['title'];
echo $rowtitle;
$row = mysql_fetch_array($result);
$rowunixdate_number = date("j", $row['unixdate']);
}
}
echo "</td>";
if (newWeek($day_count)) {
echo "</tr><tr>";
}
$day_count++;
}
The slowness is most likely because you're doing 31 queries, instead of 1 query before you build the HTML table, as Nael El Shawwa pointed out -- if you're trying to get all the upcoming events for a given author for the month, you should select that in a single SQL query, and then iterate over the result set to actually generate the table. E.g.
$sql = "SELECT * FROM events WHERE author = '$author' ORDER BY xdate ASC";
$rsEvents = mysql_query($sql);
echo("<table><tr>");
while ($Event = mysql_fetch_array($rsEvents)) {
echo("<td>[event info in $Event goes here]</td>");
}
echo("</tr></table>");
Furthermore, it's usually a bad idea to intermix SQL queries and HTML generation. Your external data should be gathered in one place, the output data generated in another. My example cuts it close, by having the SQL immediately before the HTML generation, but that's still better than having an HTML block contain SQL queries right in the middle of it.
Have you run that query in a MySQL tool to see how long it takes?
Do you have an index on the author column?
There's nothing wrong with your PHP. I suspect the query is the problem and no index is the cause.
aside from their comments above, also try to optimize your sql query since this is one of the most common source of performance issues.
let say you have a news article table with Title, Date, Blurb, Content fields and you only need to fetch the title and display them as a list on the html page,
to do a "SELECT * FROM TABLE"
means that you are requiring the db server to fetch all the field data when doing the loop (including the Blurb and Content which you are not going to use).
if you optimize that to something like:
"SELECT Title, Date FROM TABLE" would fetch only the necessary data and would be more efficient in terms of server utilization.
i hope this helps you.
Is 'author' an id? or a string? Either way an index would help you.
The query is not slow, its the for loop thats causing the problem. Its not complete; missing the $i loop condition and increment. Or is this a typo?
Why don't you just order the query by the date?
SELECT * FROM events WHERE author=? ORDER BY unixdate ASC
and have a variable to store the current date you are on to have any logic required to group events by date in your table ex. giving all event rows with the same date the same color.
Assuming the date is a unix timestamp that does not account for the event's time then you can do this:
$currentDate = 0;
while(mysql_fetch_array($result)){
if($currentDate == $row['unixdate']){
//code to present an event that is on the same day as the previous event
}else{
//code to present an even on a date that is past the previous event
//you are sorting events by date in the query
}
//update currentDate for next iteration
$currentDate = $row['unixdate'];
}
if unixdate includes the event time, then you need to add some logic to just extract the unix date timestmap excluding the hours and minutes.
Hope that helps

Categories