MySQL Query with UNIX_TIMESTAMP Not Working - php

I am trying to see if a field (end_date) in a MySQL database in the form of 2015-6-11 21:28:02 is greater than the current time. Essentially, is that field in the future or not.
Here is my PHP Code:
$current_time = time();
$sql = "SELECT member_id, course_id, FROM ".TABLE_PREFIX."vbc_status WHERE end_date < NOW()";
$result = mysql_query($sql, $db);
while ($row = mysql_fetch_assoc($result)) {
$echo $row['member_id'];
}
I keep getting an error:
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /path/to/script.php on line 373.
Line 373 is the while ($row = mysql_fetch_assoc($result)) { part.
Any ideas of how this should be fixed?

Why not skip all that and just do this:
WHERE end_date < NOW()
Converting with UNIXTIME is extremely abusive on your database, it needs to evaluate that for every row in the table and cannot use indexes. The date field itself will evaluate very quickly if indexed.

You can also set your variable format to same format used in the database.
define('DATETIME_SQL', 'Y-m-d H:i:s');
$current_time = date(DATETIME_SQL);
$sql = "SELECT member_id, course_id, FROM ".TABLE_PREFIX."vbc_status WHERE end_date < $current_time";

FOUND IT!!!
In $sql = "SELECT member_id, course_id, FROM ".TABLE_PREFIX."vbc_status WHERE end_date < NOW()"; there is an unnecessary , after course_id.
Stupid syntax.... :)

Related

Why won't this SQL statement take a string (mm/dd/yy) and convert it into days?

In my database, I have varchar values that signify dates - however I cannot input them into the database as dates. So, I am trying to pull them from the database and use them to calculate days.
Format in table:
mm/dd/yy
My SQL Statement (in PHP):
$conn = oci_connect("user", "pass", "(description=(address=(protocol=tcp)(host=host)(port=1533))(connect_data=(service_name=sid)))");
$sel = "select RECEIVED from INTOXDM.JOINT_USE where RECEIVED is not null";
$par = oci_parse($conn, $sel);
$exe = oci_execute($par);
$fetch = oci_fetch_all($par,$array);
echo $fetch;
$arraynum = 0;
while ($array) {
$arraynum = $arraynum + 1;
$date = $array[RECEIVED][$arraynum];
$today=date("m/d/y");
$now=strtotime($today); // or your date as well
$your_date=strtotime("$date");
$DAYS=($now - $your_date)/(60*60*24);
$upd = "update INTOXDM.JOINT_USE set DAYS = '$DAYS' where RECEIVED = '$date'";
$pars = oci_parse($conn, $upd);
$exe = oci_execute($pars); }
This code seems to work for some of the varchars, however many others are passed as a ridiculous value (16k days). This is because the date is being saved as 12/30/1969, I believe. This signifies that I have a problem with my date coding, but I cannot seem to figure it out.
Perhaps you should do the calculation in Oracle?
select trunc(sysdate - to_date(RECEIVED, 'MM/DD/YY'))
from INTOXDM.JOINT_USE
where RECEIVED is not null;
You can even do the update this way as well:
update INTOXDM.JOINT_USE
set DAYS = trunc(sysdate - to_date(RECEIVED, 'MM/DD/YY'))
where RECEIVED is not null;
The moral of the story is that dates should be stored in databases using the native date/time formats.

Calculate SUM in MySQL for todays date #Parse error

<?php
while($row=mysql_fetch_array($res))
{
//Result;
//select the sum in here;
$sumQry = "SELECT SUM(amount) FROM login WHERE tdate = '<?php echo date("F d, Y" ,time()); ?>" />' ";
}
?>
ERROR Parse error: syntax error, unexpected T_STRING in ... on line 4
i want to calculate the sum of numbers ( i mean like 10+50+85+90) for today date and diplsay the sum in fount end. so used the above code. but i think some thing wrong with <?php echo date("F d, Y" ,time()); ?>
UPDATE
Ok. Thanks guys! Leave about date. but i am not able to display the sum for total also.
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in ** on line 3
<?php
include "db.php";
while($row=mysql_fetch_array($res))
{
//Result;
//select the sum in here;
$sumQry = "SELECT SUM(amount) FROM login";
}
?>
I suggest you modify the MySQL table and use either DATE, DATETIME or TIMESTAMP.
They way you do it your field is CHAR or VARCHAR, that means indexing even if present will not work properly.
If you have the field as one of the above they can be indexed and performance of your query will be optimal even on a large number of records.
Thing is DATE, DATETIME and TIMESTAMP are stored numerically by MySQL. Also you will be able to sort by this field if you ever need to show more then a record and want to order by this field.
$sumQry = "SELECT SUM(`amount`) FROM `login` WHERE `tdate` = ". date("Y-m-d" ,time());
$sumQry = "SELECT SUM(`amount`) FROM `login` WHERE `tdate` = ". date("Y-m-d H:i:s" ,time());
$sumQry = "SELECT SUM(`amount`) FROM `login` WHERE `tdate` = ". time();
I also added the MySQL fields quote because even if it's not necessarily most of the time, it is a good thing to use. If you have a large JOINed query it will perform up to 5% better with them. They are also good if you by any chance use reserved words as field names.
Your code should look like this:
include "db.php";
$res = mysqli_query($con, "SELECT SUM(`amount`) FROM `login` WHERE `tdate` = '". date("Y-m-d" ,time() . "' GROUP BY `ammount`;");
$row = mysqli_fetch_array($res);
echo $row[1];
In db.php you should have something like:
$con = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
If tdate is not an INT datatype in the db you need to encapsulate the value in quotes:
$sumQry = 'SELECT SUM(amount)
FROM login
WHERE tdate = "'.date("F d, Y" ,time()).'"';

How to display table data by today's date?

I have a database called gameschedules and a table called dec1212. Inside of this table are the columns date (YYYY-MM-DD), division, field, time, team1, and team2 in that order.
I already have the data displaying on my page but I need to restrict it to only showing rows in my database that have a date that is equal to the current date. So if there are 10 rows and only 5 of them have today's date in the date column, only those should show. Here is my current query code and I know it is wrong but if someone can help me correct it that would be great:
Current code:
//specifies that it is getting data from the table and limited num rows
$result = mysql_query("SELECT * FROM `dec1212` LIMIT 0, 10 ") or die(mysql_error());
This is what I tried to do to restrict data by date:
//set variable to current date with same format as date column
$myDate = date('Y-m-d');
//pull only rows that match the current date
$result = mysql_query("SELECT * FROM 'dec1212' WHERE date = $myDate()") or die(mysql_error());
I know that my code is incorrect so this is why I am asking for help.
Try this just a signal line query
$result = mysql_query('SELECT * FROM dec1212 WHERE DATE(CONVERT_TZ(date,"+00:00","-8.00")) = DATE(CONVERT_TZ(UTC_TIMESTAMP(),"+00:00","-8.00"))') or die(mysql_error());**
$myDate = date('Y-m-d');
//pull only rows that match the current date
$result = mysql_query("SELECT * FROM `dec1212` WHERE date = '$myDate'") or die(mysql_error());
Try this
$result = mysql_query("SELECT * FROM `dec1212` WHERE `date` = CURDATE()") or die(mysql_error());
Try This
//set variable to current date with same format as date column
$myDate = date('Y-m-d');
//pull only rows that match the current date
$result = mysql_query("SELECT * FROM 'dec1212' WHERE date = $myDate") or die(mysql_error());
You are using variable not the function so just change like this
$myDate = date('Y-m-d');
$result = mysql_query("SELECT * FROM 'dec1212' WHERE date = '$myDate'") or die(mysql_error());
Make sure your date field in database containing the only date, not time
$result = mysql_query("SELECT * FROM 'dec1212'
WHERE `date`= '$myDate'") or die(mysql_error());
if your date field containing datetime datatype then use:
$result = mysql_query("SELECT * FROM 'dec1212'
WHERE `date`= date('$myDate')") or die(mysql_error());
Let the database do the work,
SELECT * FROM `dec1212` WHERE DATE(date) = DATE(NOW())
Note that $myDate is a variable, not a function. Thus, your code would be :
//set variable to current date with same format as date column
$myDate = date('Y-m-d');
//pull only rows that match the current date
$result = mysql_query("SELECT * FROM `dec1212` WHERE date = '$myDate'") or die(mysql_error());
Table name or field name should be wrapped with carat `, not single quote ' or you may omit it.
If you want to use MySQL NOW(), you need to consider time zone conversion as Raj Mohan mentioned.

strtotime php functions outputs good time in php file but wrong after update in MySQL

Ive got such script:
mysql_connect('localhost', 'xxx', 'xxx');
mysql_select_db('xxx');
$sql = "SELECT * FROM rl_cronjobs";
$sql = mysql_query($sql);
$row = mysql_fetch_array($sql);
$sunday = $row['next_sunday'];
$today = date('Y-m-d');
if($sunday == $today){
$sql = "DELETE * FROM xxx WHERE stala != 1";
$sql = mysql_query($sql);
echo $nextsunday;
$nextsunday = strtotime("next Sunday");
$nextsunday = date('Y-m-d', $nextsunday);
$sql = "UPDATE xxx SET next_sunday = $nextsunday";
$sql = mysql_query($sql) or die (mysql_error());
echo $nextsunday;
}
And in MySQL the value of it is: 1984
I need it to be normal date of next sunday
The type of MySQL table row is varchar because when i set tu date it doesn't update. Any help?
Don't store dates in varchar fields. Mysql has date, datetime, and timestamp fields for such things, and using them opens a world of new possibilities. E.g. your "next sunday" calculations can be done as simply as:
UPDATE xxx SET next_sunday = NOW() + INTERVAL (8 - DAYOFWEEK(NOW())) DAY
without ever involving the PHP time functions. Note that this particular function will always pick the real next sunday, so if you run this code on a Sunday, you'll get the following weeks' sunday, not "today", e.g.:
'2012-12-08' (Saturday) -> '2012-12-09'
'2012-12-09' (Sunday) -> '2012-12-16'
'2012-12-10' (Monday) -> '2012-12-16'
As well, note that you're trying to echo $nextsunday before it's been defined.
Looks like you missing some quotes " or ' in your update query. You probably meant to write:
$sql = "UPDATE xxx SET next_sunday = '$nextsunday'";
sidenote: The myslq_* functions are deprecated, you shouldn't use them in new code anymore.

Having trouble with MySQL double to date conversion

I have searched and searched for ways to do this but have found very limited information.
I have a MySQL table 'msgdb' that contains a field 'ttime' that is in the format double(25,8) (example row = 1352899856.95249200).
I need to routinely cleanup the table by removing any rows where the field 'ttime' is <= today's date -5 days.
These are the only two lines of code I could find related to double to time conversion but cannot get either to work.
SELECT ADDDATE(ADDDATE(ADDDATE('1899-12-31 00:00:00',FLOOR(ttime)), INTERVAL -1 DAY),INTERVAL(MOD(ttime,1)*86400)SECOND) AS TrueDate FROM msgdb
select date('1899-12-31 00:00:00'+ INTERVAL ttime * 24*3600 SECOND) as date from msgdb
I have tried first to display any rows that match the criteria using the code below, before I started using DELETE FROM to make sure I'm getting the correct results.
$query = "select date('1899-12-31 00:00:00'+ INTERVAL ttime * 24*3600 SECOND) as date from msgdb";
$result = mysql_db_query ($dbname, $query, $link);
while($row = mysql_fetch_array($result)) {
echo $row['date'];
echo '<br>';
}
and also
$query = "SELECT ADDDATE(ADDDATE(ADDDATE('1899-12-31 00:00:00',FLOOR(ttime)), INTERVAL -1 DAY),INTERVAL(MOD(ttime,1)*86400)SECOND) AS TrueDate FROM msgdb";
$result = mysql_db_query ($dbname, $query, $link);
while($row = mysql_fetch_array($result)) {
echo $row['TrueDate'];
echo '<br>';
}
but both are returning nothing.
UPDATE: Ok so by using this code:
$query = "select ttime from msgdb";
$result = mysql_db_query ($dbname, $query, $link);
while($row = mysql_fetch_array($result)) {
echo date('m-j-Y, H:i:s', $row[0]);
echo '<br>';
}
I am able to see it convert 'ttime' field from the stored value of 1352899856.95249200 to 11-14-2012, 07:30:56.
So how would I DELETE from the table all rows where ttime is <=now - 5 days?
Figuring out which records have a date before a point in time should be easy:
DELETE FROM table WHERE ttime <= DATE_SUB(NOW(), INTERVAL 5 DAY);
It might also be better to use UTC_TIMESTAMP() if you store all your times in UTC, which is the only sane way to do it.

Categories