PHP Date Function Gives Me A Wrong Time - php

I have a php datetime function that is used to insert the current date and time into mySQL database. However the date gives the right date but a wrong time any suggestion.
Below is the code.
/* Get Current Date and Time for the bookking_time field */
$booking_time=new DateTime();
$booking_time = $booking_time -> format("Y-m-d H:i:s");
// Create connection
$con = new mysqli($servername, $username, $password, $dbname , 3306);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
//mysql_select_db("$database", $con);
$sql= "INSERT INTO data_centre_users (fisrt_name,last_name,request,purpose,description,booking_time,approved)
VALUES ('$first','$last','$request','$purpose','$description','$booking_time','$approval')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
any suggestion to fix the problem

Set the timezone in the very beginning of your script file, using date_default_timezone_set();
Suppose in my case my timezone is Indian/Maldives then it would be
date_default_timezone_set('Indian/Maldives');
For a list of supported timezones refer to http://php.net/manual/en/timezones.php

It might be simpler to use the SQL Syntax NOW() to get the date and time.
$sql= "INSERT INTO data_centre_users
(fisrt_name,last_name,request,purpose,
description,booking_time,approved)
VALUES ('$first','$last','$request',
'$purpose', '$description', NOW(), '$approval')";
You may have also spelt fisrt_name wrong, but I cannot know that for sure.

First of check your date_default_timezone_set(); is proper set or not then Try like this $booking_time = date('Y-m-d H:i:s');

Related

How to update SQL data only if 1 hour is passed

I am working with a coupon code website, it has a products section. Instead of pulling data from API server of shopping sites every time a visitor loads the page, I want to store the data in SQL and use it..
But the data should update every hour or only if an hour is passed.
cron job is not required as I dont want to happen it automatically.
If there is 100 webpage users in an hour, they will get the same data, but when the first user comes after 1 hour time, it should overwrite the products's information in SQL.
I got the following code from w3schools.com and it work fine for saving data in SQL.
I hope some can help me to overwrite data only if it the data older than 1 hour. Otherwise it should act as "data already exists".
<?php
$servername = "localhost";
$username = "nuser";
$password = "pass";
$dbname = "db";
$ProductId = "smartphone";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$check=mysqli_query($conn,"select * from testdb where productid='$ProductId'");
$checkrows=mysqli_num_rows($check);
if($checkrows>0) {
echo "Data Already Exists";
} else {
//insert results from the form input
$sql = "INSERT INTO Flipkart (productid, title, price)
VALUES ('productid','title','price')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();}
?>
The above code saves data in database, it can also detect duplicate data. but I want to add just one more function, which will overwrite data if the current data time is older than 1 hour. database has a TIMESTAMP "reg_date" column, which stores created date and time in YYYY-MM-DD HH:MM:SS format.
I am new to SQL and php, so pardon me if there is any problems with the question...
You can use a cron job.
This is the best explanation with code for PHP I have found so far for cron job:
https://code.tutsplus.com/tutorials/managing-cron-jobs-with-php--net-19428

Time with PHP to MySQL

I'm a beginner in PHP and MySQL. Now I'm trying to get the date and time in MySQL. But without succes, I already been trying it for a couple of days :-(
The error message:
Error updating record: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax.
In MySQL I have given the variable timechoice the type 'DATETIME'. Is there the mistake or is it in my code? THANKS!
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$choice = $_POST["choice"];
$today = date("y-m-d h:m:s");
$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE Deelnemers SET choice='$choice' timechoice='$today' WHERE teamnaam='".$_SESSION['username']."'";
if ($conn->query($sql) === TRUE) {
echo 'antwoord verwerkt';
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
}
?>
As per your code, try using this query,
UPDATE Deelnemers SET choice='$choice',timechoice='$today' WHERE teamnaam='".$_SESSION['username']."';
Also, as you have mentioned you have this error,
Error updating record: You have an error in your SQL syntax; check the
manual that corresponds to your MariaDB server version for the right
syntax.
In MySQL I have given the variable timechoice the type 'DATETIME'. Is
there the mistake or is it in my code? THANKS!
Answer to this is, eitheir the field $today is not proper, if you have given DATETIME datatype in mysql then try this
$today = date("Y-m-d H:i:s");
P.S - I don't recommend you to use this,as your code is vulnerable.
Your SQL syntax is wrong,
$sql = "UPDATE Deelnemers SET choice = '$choice', timechoice = '$today' WHERE teamnaam = '".$_SESSION['username']."'";
Notice the commas after '$choice'.
I'd also point out several comments under your question in regards to SQL injection issues. These are important observations in ensuring DB security and handling user input.

How to retrieve time from mySQL to compare in PHP 7?

I want to insert time into MySQL and retrieve it then compare with current time.
Despite of the fact, a plenty of questions regarding to this topic, after hours of searching, most of them answered with mySQL Queries only or how to format timestamp. It is really hard to find out for my case. but I guess my problem differs. I cannot even start with the retrieved datum.
The idea is that when a data posted, it checks the last_update_time in DB with country_code. If last_update_time is within an hour, it just retrieve the time and other data. and If the the time difference is over an hour, it updates the row in DB.
The server is located on a remote site so the timezones are different.And using php 7 and mySQL 5.7
The inserting time into DB in a timezone specified works well, the last_updated_time field type is DATETIME in MySQL.
function insertData($countryCode) {
// Create connection
$conn = new mysqli(DBHOST, DBUSER, DBPASSWORD, DBNAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
date_default_timezone_set('Asia/Seoul');
$currentTime = date("Y-m-d H:i:s");
$sql = "INSERT INTO my_table (country_code, last_updated_time)
VALUES ('$countryCode', '$currentTime')";
if (mysqli_query($conn, $sql)) {
echo "INSERT Succeeded";
}else {
echo "Failed INSERT";
}
$conn->close();
}
and later I need to compare the old time(saved time) with current time when a page refreshes. I expect people from several timezones so I set date_default_timezone_set().
function compareTime($countryCode){
$conn = new mysqli(DBHOST, DBUSER, DBPASSWORD, DBNAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT last_updated_time FROM my_table WHERE country_code = '$countryCode'";
$savedTime = mysqli_query($conn, $sql);
if($savedTime->num_rows == 0) {
echo 'does not exist';
} else {
date_default_timezone_set('Asia/Seoul');
$currentTime = date("Y-m-d H:i:s");
$oldtime = strtotime($savedTime);
$timeDiffInSec = intval(strtotime($currentTime) - $oldtime) % 60;
$formattedOldTime = date("Y-m-d H:i:s",$oldtime);
echo '<p>Current Time: '.$currentTime.'</p>';
echo '<p>Old Time: '.$formattedOldTime.'</p>';
echo '<p>Time Difference: '.$timeDiffInSec.'</p>';
// Do the job only after 1 hour
if ($timeDiffInSec > 60 && $currentTime > $oldtime) {
// Do the job and update DB
}
}
$conn->close();
}
compareTime('us');
The problem I have is that I don't know how to properly get the saved time from mySQL in PHP. I cannot print the old time on the webpage or compare those two time.
Although the saved time looks like 2017-12-26 17:07:37 when I see via myPhpAdmin, those echos print like below.
Current Time: 2018-01-01 06:35:55
Old Time: 1970-01-01 09:00:00
Time Difference: 55
Even echo $savedTime; prints nothing. How can I resolve this? Thank you in advance.
$savedTime is a query result, you should fetch the results later on.
Try this:
$oldtime = strtotime(mysqli_fetch_array($savedTime)[0]);
By the way, as Funk Forty Niner reminded me on the comments, you should consider to use prepared statements to avoid SQL injection attacks. Have a look on the link, it's worth it.

how to do multiple if statemnts in php based on a criteria

I have a database named hrRecords and a table named employee in that table. It has a field named contract_end. In that field, I have the contract info of the employee specifically the duration of said contract (datetime).
What I want to achieve is to check that info to see when the contract is going to come to an end and if it is display a message saying so.
I am very new to php and I tried something but I am totally lost I was wondering if I could get some guidance of some sort thank you for your support:
<?php
$employee1= mysql_real_escape($_GET["employee1"]);
$DataBase = "hrRecords";
mysql_connect("server","username", "password") or die(mysql_error());
mysql_select_db($DataBase) or die(mysql_error());
$query = SELECT contract_end From hrRecords
// current date being compared
if(contract_end== date(Y-m-d) {
echo "something"
}
else {
echo " employe name , Your contract will expire in x amount of days "
}
/* This is the point where everything becomes fuzzy because im thinking there has to be some other way to do this for all the employees */
fist stop using mysql it has been depreciated
use either mysqli or pdo. I will show you how to do it with mysqli
<?php
$employee1= mysql_real_escape($_GET["employee1"]); // i am not sure why you are doing this since you are not using this any where
$DataBase = "hrRecords";
$ServerName = "server";
$UserName = "username";
$Password = "password";
$mysqli = new mysqli($ServerName, $UserName, $Password,$DataBase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// since i don't know all of colum names i am making them up
$stmt= $mysqli->prepare("SELECT contract_end employe_name From hrRecords");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($contract_end, $employe_name)
while($stmt->fetch()) { // this will go thorough all of the records
// current date being compared
if($contract_end== date(Y-m-d) {
echo "something"
} else {
// you need some more code here to find x
echo " $employe name , Your contract will expire in x amount of days "
}
}
i don't know if this will help you at all. you did not have enough info for a better answer

when i am entering $time=strftime('%c'); it showing value 00:00:00 in database

<?php
$con=mysqli_connect("localhost","root","","admin");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$time=strftime('%c');
$sql="INSERT INTO bookreserve(libid,bookid,issuedate ,time)
VALUES
('$_POST[libid]','$_POST[bookid]','$_POST[issuedate]','$time')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "wait for conformation";
mysqli_close($con);
?>
when i am seeing mine bookreserve table the value is sill 00:00:00 in time column
Either you've chosen the wrong modifier for strftime() as the time field must be in HH:mm:ss format. In which case you want:
$time=strftime('%H:%i:%s'); // date('H:i:s') would probably also suffice
Or you've chosen the wrong data type for your database column. If you really want the date in %c format you should change it to be a varchar. (I think varchar(23) should work).
You could also just change your query to use MySQL's own functionality:
$sql="INSERT INTO bookreserve(libid,bookid,issuedate ,time)
VALUES
('$_POST[libid]','$_POST[bookid]','$_POST[issuedate]',NOW())";

Categories