MySQL PDO NOW() as assigned value - is it possible? - php

I'm trying to pass a MySQL's NOW() function into PDO's assigned value through PHP and it's failing. I found that I must pass this directly into MySQL statement. But in my case, sometimes the datetime field can be empty.
Is it even possible to pass NOW() as PHP's assigned value?
Some code:
I'm building query dynamically and the datetime is dependent on some other variable's value.
if(isset($accountStatus)&&$accountStatus!=""){
$tmp[':account_status']=$accountStatus;
if($accountStatus==0){
$tmp[':vCodeExpire']="NOW() + INTERVAL 1 WEEK";
$tmp[':verified']=0;
}else{
$tmp[':verified']=1;
}
}
Building SQL query:
$sql="";
foreach($tmp as $k=>$v){
$sql.=str_replace(":","",$k)."=".$k.",";
}
$sql=substr($sql,0,strlen($sql)-1);
Then, I run PDO query:
$db=$pdo->prepare("UPDATE users SET $sql WHERE id=:id");
$db->execute($tmp);
I tried replacing double-quotes with single-quote around NOW() + INTERVAL 1 WEEK with no luck.
I also tried with single-quote around PDO query, but then $sql is passed directly, not using an assigned values.

is it possible?
No.
There are 2 solutions.
Calculate expiration date using PHP. Something like date('Y-m-d',strtotime('+1 week'))
Create a conditional part for the query
if(isset($accountStatus)&&$accountStatus!=""){
$tmp[':account_status']=$accountStatus;
if($accountStatus==0){
$accSql = "NOW() + INTERVAL 1 WEEK,";
$tmp[':verified']=0;
}else{
$accSql ='';
$tmp[':verified']=1;
}
$db=$pdo->prepare("UPDATE users SET $accSql $sql WHERE id=:id");

Use strtotime() instead of MySQL to get date values.

Related

PHP/mySQL get time difference by x seconds

My goal is to get the time difference between 2 different times, one from my database, and one from the client's PHP timestamp, and compare them. Then, if the time difference is less than or equal to 10 seconds, then do something.
My code, which does not work, is as follows.
date_default_timezone_set('America/Chicago');
$timestamp = date('Y-m-d H:i:s');
$sqlcheck = $dbh->prepare("SELECT timestem FROM mytable WHERE UNIX_TIMESTAMP(timestem) - UNIX_TIMESTAMP('".$timestamp."') <= 10");
$sqlcheck->execute();
if ($sqlcheck === ''){
echo "Yes";
}
else {
echo "No";
}
timestem is a DATETIME value from mySQL. $sqlcheck is meant to portray the result of the query. If the query returns nothing, then echo Yes. If it returns something from my query, then echo No.
Without getting too convoluted in explanation, my end-goal is to check how long it has been since a database operation before a client is allowed to perform updates.
You should use the MySQL built-in TIMESTAMPDIFF function:
$sqlcheck = $dbh->prepare('SELECT timestem FROM mytable WHERE TIMESTAMPDIFF(SECOND, timestem, $1) <= 10');
$result = $sqlcheck->execute([$timestamp]);
Note that instead of concatenating strings, I am providing the $timestamp as a parameterized argument.
To check the result, you can't just check for string equality. Instead, use fetchColumn on the result object:
if ($timestem = $result->fetchColumn()) {
echo "YES";
// You can also use the value of `$timestem` here.
} else {
echo "NO";
}
Note that this assumes there is only one row. For multiple rows, you need a loop. Note that only rows that match the condition are returned, so you will never see any NO output if you use a loop.
You can just as easily do the check in PHP (which will probably be a bit more straight-forward)
$sqlcheck = $dbh->prepare( "SELECT timestem FROM mytable" );
$sqlcheck->execute();
// You missed this step
$timestem = $sqlcheck->fetchColumn();
if ( time() - strtotime( $timestem ) > 10 )
print 'yes';
else
print 'no';
Some notes:
In your code you didn't actually get the value out of the database. You used the result object in your conditional
Your code implicitly assumes there is only ever one record in your table. This probably isn't true: you will need a where condition
You have to be very certain that all of your timestamps are in the same time zone
This will only work if you are using PDO, not mysqli. I can't tell the difference from your example, but a subtle difference is that PDO will allow you to use a prepare and execute with no bound parameters, but mysqli won't.

mysql timestamp output as formatted Date not working

I have a crazy phenomenon in my php script. I have defined a column as a timestamp in a mysql table. I fill it with the function:
date("Y-m-d H:i:s");
The data in the table then look like this: 2017-04-19 17:08:45
When I query this column with mysqli as a unix timestamp again:
SELECT UNIX_TIMESTAMP (timestamp) as timestampUnix FROM posts
Then binding the result using bind_result to the variable $timestampUnix.
I can echo the variable with
echo $timestampUnix;
and it outputs a correct timestamp like this: 1492614559
however if i do the following:
$timestampUnix2 = $timestampUnix;
echo $timestampUnix2;
there is simply no echo output... What is the reason?
I tried this because I actually want echo only the date in an other format with:
date('d.m.Y', $timestampUnix)
and it gave me 01.01.1970 and i wondered why the timestamp must be 0 but it isnt since when i directly echo it it gives me a correct one.
however when i do
Date('d.m.Y', 1492614559)
it gives me the correct date.. no clue what is going on there!
i know there are many other questions about mysql php Date output, but no one have this issue as i think i cannot do something with the variable i got from the query.
thanks in advance!
edit: i attach the complete code in question:
---the query that inputs the data in the db----
$timestamp = date("Y-m-d H:i:s");
mysqli_query($mysqli,"INSERT INTO posts (timestamp)
VALUES ('$timestamp')");
---the query that fetches the data----
$results = $mysqli->prepare("SELECT UNIX_TIMESTAMP(timestamp) as timestampUnix FROM posts");
$results->execute(); //Execute prepared Query
$results->bind_result($timestampUnix); //bind variables to prepared statement
$postdate = date('d.m.Y',$timestampUnix)
echo $postdate;

Comparison between a timestamp in MYSQL table with a PHP variable NOT Working - PHP MYSQL

I'm trying to filter out repeated values entering into a MySQL table, by comparing the input PHP variable with the timestamp of an entry already present in the table and only if they don't match, the input PHP variable is entered into the table.
$user1_date = mysql_real_escape_string($user1_date); // the date variable
$user1_temp1 = mysql_real_escape_string($user1_temp1);
$user1_temp2 = mysql_real_escape_string($user1_temp2);
$user1_temp3 = mysql_real_escape_string($user1_temp3);
$user1_date = date("Y-m-d H:i:s", strtotime($user1_date)); //Typecasting PHP variable into timestamp
$sql_check = "SELECT * FROM user_details WHERE temp_date ='$user1_date'";
$result_check = mysql_query($sql_check);
$num_rows_check = mysql_num_rows($result_check);
if ($num_rows_check == 0) // To check if there is no entry in the table with the same date and time as input PHP variable
{
$sql_insert = "INSERT INTO data_hour (user_id, temp1, temp_date, temp2, temp3)
VALUES (1,'$user1_temp1', '$user1_date', '$user1_temp2', '$user1_temp3')";
$result_insert = mysql_query($sql_insert);
}
temp_date is a column in the table of type timestamp. Even when the $user1_date is the same as the temp_date(timestamp) column for one of the entries in the table, it considers it as not equal and is inserting it into the table and hence I'm getting repeated values. I'm guessing the WHERE temp_date = '$user1_date'is not working properly. Some troubleshooting that I have done included
Changing '$user1_date' to just $user1_date in the WHERE
statement
Changing the WHERE clause as follows WHERE temp_date = (date)'$user1_date'
It will be great if somebody can help me out with this!
A nice easy solution would be giving temp_date a UNIQUE INDEX in your Mysql Table, as that would not allow the same value to be inserted twice. This would also make your operations more efficient, as you wouldn't have to do SELECT * every time you want to insert something.
However, for what you're doing, I think I see your problem; there are some quirks in your logic so I'll try to dispel them here. (Hopefully?) this will make your program cleaner and you'll be able to pinpoint the error, if not eliminate it altogether.
Examining this piece of code:
// $user1_date doesn't have a value here! //
$user1_date = mysql_real_escape_string($user1_date);
...
$user1_date = date("Y-m-d H:i:s", strtotime($user1_date));
Error 1 - You escape the string before ever setting a value.
What you are doing is that you are using mysql_real_escape_string() before $user1_date is ever defined.
Correction:
// Getting better, but not done. //
$user1_date = date("Y-m-d H:i:s", strtotime($user1_date));
...
$user1_date = mysql_real_escape_string($user1_date);
Error 2 - You do not give the date() function appropriate parameters
The date() function in PHP expects a timestamp, which is just an int. You can easily get the time with time(), so that should rectify your problem
Correction:
// You use strtotime($user1_date), but you should use time() //
$user1_date = date("Y-m-d H:i:s", time());
...
$user1_date = mysql_real_escape_string($user1_date);
These are small mistakes, but they can be deadly. Like I said, you should assign temp_date to a UNIQUE INDEX in your MySQL table, but make sure to correct these errors listed as well.
Let me know how it goes!

Error inserting a timestamp with pg_query_params

Im working in postgres 8.4 and PHP 5.4.3 using pg_query_params. I have a table called armies taht have 3 rows (well only for this example, it really have more). the id is an integer and the other two are timestamp withouth timezone. Now the SQL insert is:
INSERT INTO public.armies(id,build_start,build_end) VALUES ($1,$2,$3)
And the array I'm inserting is:
$data['id'] = 1;
$data['build_start'] = "now()";
$data['build_end'] = "now() + time '00:00:50'";
The error is E_WARNING: pg_query_params(): Query failed: ERROR: invalid input syntax for type timestamp: «now() + time '00:00:50'»
Its works when i tried to insert it as a raw sql using pg_query like : INSERT INTO public.armies(id,build_start,build_end) VALUES (11935,now(),now() + time '00:00:50').
So I guess it has something to do with the pg_query_params(), I really really want to insert it using pg_query_params.
What I want to achieve is sum that now() with that 00:00:50 seconds, so i can manage to alter that $data['build_end'].
Please do note that you are passing string literals
$data['build_start'] = "now()";
$data['build_end'] = "now() + time '00:00:50'";
to pg_query_params which cannot prepare a valid date/time value from "now()" or "now() + time '00:00:50'".
Instead of
INSERT INTO public.armies(id,build_start,build_end) VALUES ($1,$2,$3);
change it to
INSERT INTO public.armies(id,build_start) VALUES ($1,now());
and remove the parameters
$data['build_start'] = "now()";
$data['build_end'] = "now() + time '00:00:50'";
Now when the action completes, update the table.
UPDATE public.armies SET build_end=now() WHERE id=$1;
Hope I was able to help you.

How to grab items from a DB by date

This is my script:
$spending_period = time() - (30 * 24 * 60 * 60);
$spending_period = date('Y-m-d', $spending_period);
$monthly_income_query="SELECT amount FROM budget_items WHERE (date_code >= '$spending_period') && (type=='Income') ORDER BY date_code DESC";
$monthly_income_result=mysql_query($monthly_income_query);
while($monthly_income_scan=mysql_fetch_array($monthly_income_result)){
if($montly_income_counter >=1){
$monthly_income=$monthly_income + $monthly_income_scan['amount'];
}
}
I receive an error that mysql_fetch_array() is not a valid result resource.
The goal is to grab only items in the budget_items table that have a date_code (using the DATE type) occurring within the last 30 days.
Anyone have suggestions?
If something doesn't work with your
query - you may want to try it out in
mysql console with some sample date.
If data is returned, then try printing out a query. I have a hunch that $spending_period variable might not be interpolated correctly into your query string (try using '{$spending_period}' instead of '$spending_period'.
You need to format the date as a strong and use CAST inside the select statement to accept the value as a date value.

Categories