Hi I try to Auto Load Page on Every Week Sunday Night 9.00pm using php mysql, Please Help Anyone.,
Here is my Execute code
date_default_timezone_set("Asia/Kolkata");
$con = mysqli_connect("localhost","root","","chat");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$current_date = date('Y-m-d');
$date_title = "TODAY";
mysqli_query($con,"insert into date(date_title, date) values('$date_title', '$current_date')");
=> use cron job ..
Check this url :-
How to run crontab job every week on Sunday
OR
https://www.thegeekstuff.com/2009/06/15-practical-crontab-examples
Related
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']));
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
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.
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');
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!');
...