mysql timestamp output as formatted Date not working - php

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;

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.)

How to pass in a variable that was created with date() function to a MYSQL table with php

I receive a GET variable named $temp in my php code, after connecting to the server and selecting the correct database, and I am able to pass it into the table using:
mysql_query("INSERT INTO Temperature (Temperature) VALUES ($temp)");
However if I save a time variable using:
$time = date('G:i', time());
and try and pas it in with:
mysql_query("INSERT INTO Temperature (Temperature) VALUES ($temp)");
or even:
mysql_query("INSERT INTO Temperature (Time,Temperature) VALUES ($time,$temp)");
I am unable to get it to be passed into my table.
I am echoing both variables so I know they are being saved correctly into the variables. Also, in my table there are two columns named "Time" and "Temperature". The name of the table is "Temperature". Why won't the $time variable get passed in if it is the exact same line of code as $temperature variable except for changing the column name? Also both columns are set to recieve varchar (20) could this be the issue?
You're very close to having it right in your example. In this line you need quotes in your query around your values.
mysql_query("INSERT INTO Temperature (Time,Temperature) VALUES ($time,$temp)");
So it would look like this:
mysql_query("INSERT INTO Temperature (Time,Temperature) VALUES ('$time', '$temp')");
But this way of creating a query is soon to be deprecated for the easier to use and more modern method of using PDO. Using PDO would looking something like this:
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare('INSERT INTO Temparature (`time`, `temperature`)
VALUES (:time, :temperature)');
$stmt->bindParam(':time', $time);
$stmt->bindParam(':temperature', $temp);
// insert a row
$temp = "34";
$time = date('G:i', time());
$stmt->execute();
A time column in MySQL expects a string in the format 'hh:mm:ss'.
To do this, you could do:
$timestamp = time();
$time = date('G:i', $timestamp); // assuming you need $time somewhere else
mysql_query("INSERT INTO Temperature (Time,Temperature) VALUES ( ".date('H:i:s', $timestamp).", $temp)");
If you do not need $time for any other purpose than inserting it in the database, you could use:
mysql_query("INSERT INTO Temperature (Time,Temperature) VALUES (NOW(), $temp)");
And let MySQL do the time creation for you.
To only select the hours and minutes do:
SELECT TIME_FORMAT(Time, '%H:%i') FROM Temperature;
See the MySQL Documentation for more info on formatting date and time as strings.

php insert prepared stmt

My code looks like:
$sql_ = $this->db->prepare("SELECT * FROM user");
$sql_->execute();
$user = $sql_->fetchAll();
$sql_insert_blog = $this->db->prepare("INSERT INTO
blog
(blog_title,blog_author,blog_content,blog_tags,blog_create,blog_update)
VALUES
(:1,:2,:3,:4,:5,:6)");
$sql_insert_blog->execute(array(
":1"=>$title,
":2"=>$author,
":3"=>$content,
":4"=>$tags,
":5"=>$date_create,
":6"=>$date_update
));
So the first sql statement is to proof if the database coneccion is active. It works when i use
print_r($user)
Th second one is the statement thats not been executed.
I have a controller that calls this function on a model, and gives all the info from the form to this function like
function newBlogEntry()
{
$title = $_POST["input_blog_title"];
$author = $_POST["input_blog_author"];
$content = $_POST["input_blog_content"];
$tags = $_POST["input_blog_tags"];
$date_create = date('m/d/Y h:i:s a', time());
$date_update = $date_create;
$this->model->newBlogEntry($title,$author,$content,$tags,$date_create,$date_update);
}
and the function on this model is actually called. i can select all users from db.
i allready checked all the parameters, and also every parameter can be null so, even if the form is emtpy it should be a insert in the database(This is just for testing).
But there is no entry in the database...
So my question is: what am i doing wrong here?
It would appear that MySQL doesn't like your date values. The default format for dates-as-strings in MySQL is YYYY-MM-DD HH:MM:SS, according to the docs; a string that looks like this will automatically be parsed as a date.
use (?,?,?,?,?,?) instead of (:1,:2,:3,:4,:5,:6)
and
$sql_insert_blog->execute(array($title, $author, $content, $tags, $date_create, $date_update));
and
dates should be strings with Y-m-d H:i:s php date() format

Why Php explode is echoing but can't post

i have exploded timestamp2w to date and time. I can post the date to the database but the time isn't posting, but if i echo it, it is showing the time. i want to post that time to the db.
$timestamp3=$_POST['timestamp'];
$timestamp3x=explode(" ",$timestamp3);
$timestamp=$timestamp3x[0];
$timestamp3=$timestamp3x[1];
$datetime=$_POST['$timestamp3'];
$transactiondate =date("Y-m-d");
$userid=$_SESSION['userid'];
$equipmentid = $_GET['id'];
echo $timestamp3;
$sql="Insert into tbl_booking(equipmentid,book_to,book_from,transactiondate,user_booked,datetime)VALUES('$equipmentid','$timestamp2','$timestamp','$transactiondate','$userid','$datetime')";
i think you have time value in $timestamp3 and you are sending $timestamp2 to mysql query so change your query like below
$sql="Insert into tbl_booking(equipmentid,book_to,book_from,transactiondate,user_booked,datetime)VALUES('$equipmentid','$timestamp3','$timestamp','$transactiondate','$userid','$datetime')";
you're echoing $timestamp3 variable, but in the query I can see $timestamp2!

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!

Categories