PHP date insert using datepicker - php

My PHP script writes "Data entered!", but there are no records in the database. Here is the code.
<?php
$startdate = $_POST['start'];
$enddate = $_POST['end'];
$type = $_POST['type'];
if ($startdate && $enddate && $type) {
$con=mysqli_connect("localhost", "root", "")or die("Can not connect to DB");
mysqli_select_db($con,"booker")or die("Can not select DB");
mysqli_query($con,"INSERT INTO events(start_date,end_date,type) VALUES('$startdate','$enddate','$type')");
echo "Data entered!";
}
else {
echo "Please fill in the form!";
}
?>
I select dates using datepicker and type is selected through select option in html (3 options available). Names of html form fields are start, end, type. Fields in DB are start_date, end_date, type. PHP script runs with no errors and everything seems ok, but there are no records in DB.

Nothing wrong with your PHP script. It just comes from the input. Make sure you have a standard format like
"YYYY-MM-DD" (use - 'hypen').
MySql won't respond if you use outside of that format, for example
"YYYY/MM/DD" -> this won't work.

Send all dates you want to INSERT with SQL through date() like so:
$date = date('Y-m-d', strtotime($_POST['date']));

Related

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.

Is there a way to add current date to a received JSON in php?

I have an andriod app sending data in JSON to a php script and appending it to a mysql table, is there any way to insert the current date without adding it to the app. I am trying to get php to add the current date to BoughtDate inside the same query.
<?php
error_reporting(E_ALL); ini_set('display_errors',1);
include('../htconfig/dbConfig.php');
$dbSuccess = false;
$dbConnected = mysql_connect($db['hostname'],$db['username'],$db['password']);
if ($dbConnected) {
$dbSelected = mysql_select_db($db['database'],$dbConnected);
if ($dbSelected) {
$dbSuccess = true;
}
}
$data_back = json_decode(file_get_contents('php://input'));
$userName = $data_back->{"User"};
$password = $data_back->{"Pword"};
$BoughtFrom = $data_back->{"Bfrom"};
$VIN = $data_back->{"VIN"};
$Color = $data_back->{"Color"};
$MakeIndex = $data_back->{"Make"};
$ModelIndex= $data_back->{"Model"};
$Year = $data_back->{"Year"};
$Bid = $data_back->{"Bid"};
$INV = $data_back->{"PurchasePrice"};
$BidContact = $data_back->{"Contact"};
$BidEmail= $data_back->{"Email"};
mysql_query("Insert Into tblinventory (VIN, MakeIndex, ModelIndex, Year, Color, Bid, INV,
BidContact, BidEmail, BoughtFrom, BoughtDate)
VALUES ('$VIN','$MakeIndex', '$ModelIndex', '$Year', '$Color', '$Bid',
'$INV', '$BidContact', '$BidEmail', '$BoughtFrom', '$BoughtDate'") or die (mysql_error());
$responses = array();
{
$responses[] = array( $VIN . " " . $MakeIndex . " " . $ModelIndex." ". $Year." " );
}
header("Content-type: application/json");
echo json_encode($responses);
?>
As first the var $BoughtDate is not existent in your current code.
You can fill $BoughtDate by using php function time wich returns the current unix timestamp.
See http://php.net/time for further explanation.
Code Snipped:
$BoughtDate=time();
Let mysql do that for you using CURDATE. See this article for more details.
There are a couple of things, that needs your attention.
First the $data_back->{"bar"}, is a unnecessary syntax. Instead use $data_back->bar. (usefull comments below answer on this subject) Also the " is for string parsing, you can replace it with a ' as long as it is only a string without variables.
Secondly the mysql_connect, mysql_select_db and mysql_query functions are deprecated (check the php manual and the big warning box in each of these function).
The query is vulnerable to SQL injection (serious security issue).
Instead use mysqli or pdo and prepared statements. You can find tons of resources on this subject on google.
See #gview answer for info on inserting the date in the column, make sure the column type matches.

Inserting today date from form to database

I'm trying to insert date when form is processed but in MySQL is inserting like
0000-00-00
I don't want user to insert date.
Here is my form
<form action="upload.php" method="post" enctype="multipart/form-data">
<textarea type="text" name="text" cols="40" rows="10"></textarea><br />
<input type="hidden" name="dt"/>
<input type="submit" name="upload" id="upload" value="Изпрати" />
And this is upload.php
<?php
if (isset($_POST['upload'])) {
$text = $_POST['text'];
$dt = date('Y-m-d', strtotime($_POST['Date']));
$db = new mysqli("localhost", "*****", "", "****");
if (mysqli_connect_error()) {
printf("Connect failed: ", mysqli_connect_error());
}
mysqli_set_charset($db, "UTF8");
$query = "INSERT INTO table (text, date) VALUES (?, ?)";
$conn = $db->prepare($query);
if ($conn == TRUE) {
$conn->bind_param("si",$text, $dt );
if (!$conn->execute()) {
echo 'error insert';
} else {
header("Location: ../admin/index.php");
exit;
}
} else {
die("Error preparing Statement");
}
} else {
echo 'error';
}
?>
What can be the problem?
edit:
In mysql the row for date is type - 'date'
edit2:
I forget about NOW()... is working perfect and is so simple.
I don't want user to insert date.
Then don't make it a part of the user-submitted form. As it stands, even if it's a hidden element, users can modify it to insert whatever date value they want. You don't want the user to insert the date, but your current code requires that the user insert the date.
If you just want it to be a system-known date, you can do this entirely in the INSERT statement at the database level:
INSERT INTO table (text, date) VALUES (?, NOW())
That way the database itself generates the current date, instead of relying on whatever the user submits. At this point you can completely remove the date input from the form and remove the parameter from the PHP code that builds the database query.
if you don't want user to be insert date than handle it at server side. My answer is for handle using PHP otherwise you can also go with NOW() mysql side handling.Choice up to you :
$dt = date('Y-m-d: H:i:s');
OR you can store it in databse as timestamp:
$dt=date("Y-m-d H:i:s");
$dt= strtotime($dt);
and retrieve it at front
date("Y-m-d H:i:s",$dt)
Replace in your code:
$query = "INSERT INTO table (text, date) VALUES (?, NOW())";

How to display date and time in webpage continuously and update in MySQL database simultaneously?

I want to display time in the web page every second and update in the MySQL database simultaneously for my project. I tried it with PHP. But the page needs to be refreshed every second to do this. Making a server call every second dosen't seem like a good idea to me. Is there any other way to do this?
<?php
$url1=$_SERVER['REQUEST_URI'];
$username = "root";
$password = "root";
$hostname = "localhost";
date_default_timezone_set('Asia/Calcutta');
$date = date('m/d/Y h:i:s a', time());
echo ("Date: $date");
$dbhandle = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
mysqli_select_db($dbhandle, "testing") or die("Cannot select database");
$sql = "INSERT INTO data ".
"(date)".
"VALUES ( '$date')";
mysqli_query( $dbhandle,$sql );
header("Refresh: 1; URL=$url1");
?>
You can have an element on the page to both display the date/time and write to the database. Use an interval to trigger ajax calls:
<html>
<body>
<span id="mytime"></span>
<script src="http://www.antradar.com/download/nano.js"></script>
<script>
setInterval(function(){
ajxpgn('mytime','updatetime.php?');
},1000); //update every second
</script>
</body>
</html>
The updatetime.php code would be the same as yours, except that you want to omit the header part.
The ajxpgn function in the Nano Ajax library is similar to the ajax updater function in prototype.js and jQuery, except that if a second request is sent to server and the first request is still in flight for any reason, the first request is canceled to avoid congestion.

CRON isn't working

I have the following php code set to run as a CRON job. It runs once a day and never returns an error so I assume it is running properly. The problem is, the rows aren't being deleted from my database!
I've tested the php and the variables work. I've tested my query and that works too so I'm at a loss...
<?php
$isCLI = ( php_sapi_name() == 'cgi-fcgi' );
if (!$isCLI)
die("cannot run! sapi_name is ".php_sapi_name());
exit;
//Connect to DB
mysql_connect("xxxxxx.com", "xxxxxxxxxx", "xxxxxxxxxxxx") or die(mysql_error());
mysql_select_db("xxxxxxxxxxx") or die(mysql_error());
//Get today's date
$todayis = date("Y-m-d");
$todayis = strtotime(date("Y-m-d", strtotime($todayis)) . " -4 hours");
$todayis = date('Y-m-d', $todayis);
//Delete rows in userContests where reminder is less than or equal to today's date
mysql_query("DELETE FROM userContests WHERE reminder <= '$todayis';") or die(mysql_error());
?>
Can someone explain to me why the rows won't delete?
If that is the whole script, I would say you have forgotten to connect to the database.
Edit: This seems to be the problem:
if (!$isCLI)
die("cannot run! sapi_name is ".php_sapi_name());
exit;
That translates to:
if (!$isCLI)
{
die("cannot run! sapi_name is ".php_sapi_name());
}
exit;
So basically you always stop your script on the 6th line, nothing after that will ever be executed.
If it is a CRON job, it should be using PHP-CLI not PHP-CGI. You can add this to the top of the file to do the right check.
<?php if(PHP_SAPI != 'cli') throw new Exception('Not in CLI mode!');
...

Categories