hey stackoverflowers. im having a few problems with the code i have written to check my database on refresh if all record dates on the database are between the specified $min and $max values. if not then the record will be updated. this is what i have done so far.
// check database for necessary updates
$update = mysql_query("SELECT * FROM rent");
while($row = mysql_fetch_array( $update )) {
$datetime_lower = DateTime::createFromFormat('d/m/Y', $min);
$datetime_upper = DateTime::createFromFormat('d/m/Y', $max);
$datetime_compare = DateTime::createFromFormat('d/m/Y g:i a', $row_update['pDate']);
$diff_lower = $datetime_lower->diff($datetime_compare);
$diff_upper = $datetime_upper->diff($datetime_compare);
if ($datetime_lower < $datetime_compare && $datetime_upper > $datetime_compare) {
// date is between min and max, do nothing
} else {
// date is not between min and max, update cell colour
$result = mysql_query("UPDATE rent SET colour='F0F0F0' WHERE $datetime_lower < $pDate && $datetime_upper > $pDate") or die(mysql_error());
}
}
the logic behind it seems rather rational but whenever i try to run the code i get the error message:
Warning: DateTime::diff() expects parameter 1 to be DateTime, boolean given in C:\xampp\htdocs\keypad\main.php on line 41
Warning: DateTime::diff() expects parameter 1 to be DateTime, boolean given in C:\xampp\htdocs\keypad\main.php on line 42
any idea whats going on?
fetching into $row but using $row_update
UPDATE rent SET colour='F0F0F0' will update ALL records if one tupel is not between $min and $max
Why not UPDATE rent SET colour='F0F0F0' WHERE pDate NOT BETWEEN $min AND $max MySQL Between
I think your approach is not optimized, instead of compare the different from php->mysql->php, you can issue a query to directly update to mysql, like
update rent set colour='F0F0F0' WHERE pDate>='$min' and pDate<='$max';
Related
I have the statement below that changes what is displayed depending on what time/day it is.
<?php $new = $mysqli->query("SELECT latedate FROM skiptonevents WHERE status='Active' ORDER BY id DESC LIMIT 1");
while($row = $new->fetch_assoc()) {
$late=$row["latedate"];
if($late < $datetime){
include_once('skiptonone.php');
}
else {
include_once('skiptontwo.php');
}
}
?>
In my database I have a column called latedate (0000-00-00 00:00:00).
$datetime = date('Y/m/d H:i:s');
I am trying to make it show (skiptonone.php) if todays date ($datetime) is less than latedate in the database ($late).
If latedate is after todays date to show skiptontwo.php
Could you please point me in the right direction as my current code does not work properly. It only shows skiptonone.php at the moment regardless of what time is in latedate.
Change
if($late < $datetime){
for
if(strtotime($late) < time()){
This is because you're doing string comparison otherway.
I am building a php application using pgsql as its back end.
I would like to increment the date by some amount of date shich should be loaded from my database which have given value as available=1,3,5(implying monday,wednesday,friday of a week).I would like to increment these available values to current date. I am using N format in date() function to represent the values of days in a week as 1 to 7 which is stored in available field in the database
If current date =22-07-2013 which is monday,then i have to increment this to wednesday(available=3) and then to friday(available=5) And then to monday of the next week.
And so on..
but i cant do that..
i am in need of such a code where the value of available may change according to the tuples in that tuple.So i would like to increment the current date based on the value of available.
So please help me to achieve it.
The code I used is attached herewith.Please have a look at it.
<?php
$sq = "SELECT * FROM $db->db_schema.dept where active='Y' and dept_id=$dept_id";
$result = $db->query($sq);
$ftime=$result[0]['f_time'];
$ttime=$result[0]['t_time'];
$a=date('Y-m-d').$ftime;
$b=date('Y-m-d').$ttime;
$to_time = strtotime("$b");
$from_time = strtotime("$a");
$minutes= round(abs($to_time - $from_time) / 60,2). " minute";
$days=array();
$days= explode("," , $result[0]['available']);
$result[0]['available'];
$intl=$result[0]['slot_interval'];
$slots=$minutes/$intl;
$dt1 =date("m/d/Y $ftime ");
$s_mnts=explode(":",$ftime);
$m= date('N');
-- $dt=array();
$a=$dt1;
$l=0;
for($n=1;$n<=3;$n++)
{
for($k=$m;$k<=7;$k++)
{ $l=$l+1;
if(in_array($m,$days))
{
echo "dasdsa";
echo date("Y-m-d H:i:s", strtotime("$a +$l days"));
echo"<br>";
}
$m=$m+1;
if($m==7){$m=1;}
}
}
?>
where
dept_id -> primary key of the table dept
$db->query($sq); -> query is used to fetch the given values and is defined in another file named database.php in the program folder.
f_time and t_time -> fields in the table dept which describes the from_time and to_time.f_time is the time from which we have to start increment and t_time is the time to end this increment.
Please inform me whether there is any improvement in the code I have given. .
What you could do is something like this:
You say how many days you want to increment. And give an array of availables.
<?php
$inicialDate = time(); //Timestamp of the date that you are based on
$tmpDate = $inicialDate; //Copy values for tmp var
$increment = 5; //Increment five days
$available = [1,3,5]; //Days available
/*Ok, now the logic*/
while($increment > 0){
$tmpDate = strtotime("+1 day", $tmpDate); //Increase tmpdate by one day
if(in_array(date("N",$tmpDate), $available){ //If this day is one of the availables
$increment--;
}
}
$finalDate = date("m/d/Y",$tmpDate);
?>
This logic should work, although I don't know how to reproduce it via a SQL Procedure.
From what I can tell, you are after something like
UPDATE sometable
SET some_date_column = some_date_column + ('1 day'::INTERVAL * some_integer_value);
I found this great function on SO whilst looking for a way to generate random dates between two fixed timestamps:
function randomDate($start_date, $end_date)
{
// Convert to timestamps
$min = strtotime($start_date);
$max = strtotime($end_date);
// Generate random number using above bounds
$val = rand($min, $max);
// Convert back to desired date format
return date('Y-m-d H:i:s', $val);
}
Source and credit
but I am looking for a way for the dates to be generated in order (start date to end date) as I have used it to generate dates to insert into a database.
The problem is my posts are ORDER BY id DESC and using the function "as is" being that they are random the dates end up out of sync.
ie:
post id 4 - date = 2010-07-11 14:14:10
post id 3 - date = 2012-02-22 18:23:21
post id 2 - date = 2011-03-17 13:52:47
post id 1 - date = 2011-08-14 15:33:50
and I need them to be in sync with the post id.
Now your thinking why not change the query to ORDER BY date DESC instead? ...well that would mess up 99% of code I have already written as there are other columns/rows dependent on it being ORDER BY id DESC and so ordering the dates when being inserted into the database is the only solution.
update:
this is what I tried using madfriend code but all dates are the same where have I gone wrong?
function randomDate($startdate, $enddate){
$min = strtotime($startdate);
$max = strtotime($enddate);
$val = rand($min, $max);
return date('Y-m-d H:i:s', $val);
}
$query = "SELECT * FROM foo";
$num = mysql_num_rows(mysql_query($query));
$randate = randomDate('2010-07-12 09:13:40', '2012-06-12 09:13:40');
$dates = array($randate);
for ($i = 0; $i < $num; $i++) {
$dates[] = randomDate($startdate, $enddate);
}
sort($dates);
while($date = array_shift($dates)) {
$update = "UPDATE foo SET date='{$date}'";
mysql_query($update);
}
plus getting
Notice: Undefined variable: startdate
I'm not quite sure whether you are talking about creation or modification of existing rows.
Updates: basic idea here is quite simple. First, count number of posts with SELECT COUNT(*) FROM your_posts_table query. After that:
// $num is number of posts
$dates = array();
for ($i = 0; $i < $num; $i++) {
$dates[] = randomDate($startdate, $enddate);
}
sort($dates); // Sort dates in ascending order
while($date = array_shift($dates)) {
// now $date won't be lower than it was in previous iterations.
// use it to update your table
}
Insertions: If you are talking about insertions and want to make latest post date random but biggest, here's what you do:
First, select last added post date.
Second, call randomDate with $startdate set to the date of last added post.
Last, insert new row with this date.
function randomDate($startdate, $enddate){
$min = strtotime($startdate);
$max = strtotime($enddate);
$val = rand($min, $max);
return date('Y-m-d H:i:s', $val);
}
$query = "SELECT * FROM foo";
$num = mysql_num_rows(mysql_query($query));
$randate = randomDate('2010-07-12 09:13:40', '2012-06-12 09:13:40');
$dates = array($randate);
for ($i = 0; $i < $num; $i++) {
$dates[] = randomDate($startdate, $enddate);
}
sort($dates);
while($date = array_shift($dates)) {
This query updates all rows in one go:
$update = "UPDATE foo SET date='{$date}' ";
mysql_query($update);
}
Probably were wanting to use
$update = "update foo set date='{$date}' where id = (select id from foo where date is not null order by id limit 1)";
(for that to work you need to set each date in the db to null before you start updating: update foo set date=null)
Also you shouldn't be using myslq_query..
Hey everybody. I am trying to print out a schedule with thirty minute intervals and would like to query a DB to get whatever thing is happening at that time. If i manually enter the time (hour, minute, am/pm(months, year, day work as is)) i get events. It's just when i let the query pull the time from the loop this doesnt work. Any ideas?
$day = date('d');
$year = date('Y');
$month = date('m');
$start = mktime(0,0,0);
$thing_query="SELECT thing FROM things WHERE day='$day' AND month='$month' AND year='$year' AND hour='$hour' AND minute='$minute' AND ampm='$am'";
$result=mysql_query($thing_query);
for($min = 0; $min < 24 * 60 * 60; $min += 30 * 60)
{
$hour=date("h", $start + $min);
$minute=date("i", $start + $min);
$am=date("A", $start + $min);
while ($row=mysql_fetch_array($result)) {
$thing = $row[0];
}
printf("<tr><td>%s</td><td>$thing</td></tr>",
date("g:i a", $start + $min));
}
Variable references in a string are only valid at assignment; they don't continue to update if you change those variables, so when you do
$thing_query="SELECT thing FROM things WHERE day='$day' AND month='$month' AND year='$year' AND hour='$hour' AND minute='$minute' AND ampm='$am'";
it's equivilent to
$thing_query="SELECT thing FROM things WHERE day='15' AND month='2' AND year='2011' AND hour='' AND minute='' AND ampm=''";
because $hour, $minute and $am haven't been set, and thus the query returns nothing.
Even if they were, updating the string won't update the database query; you'll need to call mysql_query() on the new string to get that data.
If you move the $thing_query= and $res= lines to just before the while loop this should work, although it will only return the last event in each timeslot, because you're overriding $thing each time you go through the loop. It will also continue to list an event in every timeslot until it reaches a new one, because you're not clearing $thing.
As Andy says, this isn't currently a very efficient way to do what you want, but since you're presumably just starting out I'm guessing its more important to you for now that it works rather than being efficient, so hopefully this helps for now.
I would imagine this is because you are not setting hour minute and ampm before you query the database.
You probably need to requery the DB every cycle through the loop with the new hour, minute etc, however there is probably a more efficient way of doing this... i.e. Hit the db once for the whole days data, then use PHP to iterate out the info. 1 db call insted of 24*60*60
The below code is untested so please call me up on it if it doesn't work entirely but it should give you an idea:
$day = date('d');
$year = date('Y');
$month = date('m');
$start = mktime(0,0,0);
$thing_query="SELECT thing FROM things WHERE day='$day' AND month='$month' AND year='$year';
$result=mysql_query($thing_query);
while ($row=mysql_fetch_array($result)) {
// Loop through your hours mins etc and output desired values
}
}
All the data you need is stored in mysql_fetch_array($result) you can then loop through that where required. You dont want to be hitting the DB more than is necessary.
From what i can see you have the PHP to be able to do it - i think its a structure thing you are struggling with.
Your loop structure is wrong - you are consuming the entirety of the query result set on your first run around the parent for loop. And your internal while loop is simply setting $thing to the value of one field repeatedly, so $thing ends up being the LAST value returned from the query.
comment followup. An inefficient method of doing what you want would be:
$day = ...
$year = ...
$month = ...
$start = ...
for ($min = 0; ....) {
$hour = ...
$min = ...
$am = ...
$thing_query = "SELECT ...."
$result = mysql_query($thing_query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
printf(.... $row[0] ... );
}
}
But this would run a query for every single time point you're checking for. Why not just store the event's date/time in a single date/time field. YOu can reduce your query to
SELECT ... WHERE timestampfield BETWEEN startdatetime AND enddatetime
then use the results of that in PHP to build up your events. A single "larger" query would be more efficient than a long series of "small" ones.
You mixed up the order of your statements pretty badly. Here's the right way, and some additional comments:
$day = date('d');
$year = date('Y');
$month = date('m');
$start = mktime(0,0,0);
for($min = 0; $min < 24 * 60 * 60; $min += 30 * 60)
{
$hour=date("h", $start + $min);
$minute=date("i", $start + $min);
$am=date("A", $start + $min);
// you must set the string after $hour/$minute/$date have the right value
$thing_query="SELECT thing FROM things WHERE day='$day' AND month='$month' AND year='$year' AND hour='$hour' AND minute='$minute' AND ampm='$am'";
// query the database with the string
$result=mysql_query($thing_query);
// put things in an array
$things = array();
while ($row=mysql_fetch_array($result)) {
$things[] = $row[0];
}
// join the array so I have a comma separated list of things
$listOfThings = implode(", ", $things);
// ALWAYS use htmlspecialchars when sending data from the database to the browser!!!!
echo "<tr><td>" . date("g:i a", $start + $min) . "</td><td>" . htmlspecialchars($listOfThings) . "</td></tr>";
}
Upon running the below SQL statement (which works perfectly) I've found that all tables in my database are flushed white.
Any idea as to why this happening?
// check database for necessary updates
$update = mysql_query("SELECT * FROM rent WHERE colour='3C0'");
while($row_update = mysql_fetch_array( $update )) {
$datetime_lower = DateTime::createFromFormat('d/m/Y', $min);
$datetime_upper = DateTime::createFromFormat('d/m/Y', $max);
$datetime_compare = DateTime::createFromFormat('d/m/Y g:i a', $row_update['pDate']);
if ($datetime_lower < $datetime_compare && $datetime_upper > $datetime_compare) {
// date is between do nothing
mysql_close($update);
} else {
// date is not between so update
echo "date is not between";
$update_result = mysql_query("UPDATE rent SET colour='F0F0F0' WHERE substr(pDate, 0, 10) NOT BETWEEN $min AND $max && colour='3C0'");
mysql_close($update_result);
}
}
I've included a few pictures.
This is how it is meant to look like (above code omitted):
http://i51.tinypic.com/143gpef.jpg
This is how it currently looks like (above code present):
http://i54.tinypic.com/2lwm4xg.jpg
Your while loop appears to go through all the results from your table. It appears that on each iteration of the loop, you check the date first in PHP, then you check the date again in your update query, and update all matching rows to F0F0F0.
I don't know why your code is changing the colour to white instead of #F0F0F0, since there is no white or fff in your code, so all I can do is suggest something to make your code more efficient.
Instead of updating all rows on each iteration of the while loop, if you have an id column (Primary Key with Auto-increment) in your rent table, you can use this value in your while loop instead of having to test the date a second time.
$update = mysql_query("SELECT * FROM rent WHERE colour='3C0'");
while($row_update = mysql_fetch_array( $update )) {
$datetime_lower = DateTime::createFromFormat('d/m/Y', $min);
$datetime_upper = DateTime::createFromFormat('d/m/Y', $max);
$datetime_compare = DateTime::createFromFormat('d/m/Y g:i a', $row_update['pDate']);
if ($datetime_lower < $datetime_compare && $datetime_upper > $datetime_compare) {
// date is between do nothing
mysql_close($update);
} else {
// date is not between so update
echo "date is not between";
$update_result = mysql_query("UPDATE rent SET colour='F0F0F0' WHERE id=" . $row_update['id'] . " && colour='3C0'");
mysql_close($update_result);
}
}