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!');
...
Related
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.
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
im trying to update date on the table. YYYY-MM-DD HH-MM-SS.
There is the code i have.
It takes information from table and after that I want it to set date in that table to current time
<?php
$username = "root";
$password = "sawasq";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
$code = $_POST['kodas'];
$code = stripslashes($code);
$sql = mysql_query("SELECT * FROM dviraciai WHERE ID='$code'");
$Pavadinimas = 'Pavadinimas';
$Metai = 'Metai';
$Status = 'Status';
$rows = mysql_fetch_assoc($sql);
echo 'Pavadinimas: ' . $rows[$Pavadinimas] . '<br>';
echo 'Metai: ' . $rows[$Metai] . '<br>';
echo 'Status: ' . $rows[$Status] . '<br>';
$sql2 = mysql_query("UPDATE Dviraciai WHERE ID='$code' SET date=CONCAT(CURDATE(),' ',time(mytime))");
mysql_close();
?>
I get $code from input.
Dviraciai is my table.
I dont get any error. But when i enter my $code it shows the info but doesnt change time in table after I restart phpMyAdmin
Your query is totally wrong, and since you never bother checking for errors and simply ASSUME nothing could ever go wrong...
Update syntax is
UPDATE ... SET ... WHERE...
You have the set/where reversed. And note that restarting phpmyadmin is beyond pointless. It's a MANAGEMENT INTERFACE. It's not the database itself. It's like trying to change the outcome of a tv show by turning your tv on/off.... the show's going to end up broadcasting the same ending no matter what you to do with your TV.
Never assume success with DB operations. Even if your SQL is 100% syntactically perfect (and yours definitely isn't), there's far too many OTHER reasons for a query to fail. Assuming success is, frankly, just plain stupid. Always assume failure, check for failure, and treat success as a pleasant surprise. At bare minimum, have something like this:
$result = mysql_query(...) or die(mysql_error());
$query = "SELECT `ip` FROM `banned` WHERE `ip` = '$ip'";
$retval = mysqli_query($conn, $query);
if(!$retval){
die("Could not Execute Query: " . mysqli_error($conn));
} else {
if(mysqli_num_rows($retval) == 0){
echo "test";
} else {
header('Location: http://www.teutonic-development.net/index.php?p=banned');
}
}
when I'm running this code all that's printed out is: "Could not Execute Query:"
I really have absolutely no idea why it's doing this. I'm connecting fine in my init.php file. Which is where this file is.
My other script which just adds a log entry works fine. And if I run my $query in phpmyadmin's sql interpreter it runs perfectly fine (when I replace the $ip part with an actual ip of course)
Any suggestions?
Normally one would say that hey your query failed to execute story finish. But this case is interesting.
Your code is
die("Could not Execute Query: " . mysqli_error($conn));
and your error message is
Could not Execute Query:
Notice even though you have mysqli_error($conn) but there is no mysql error being shown. That confirms 100% that $conn is not properly established (contrary to what you think)
So take a look at your code again and see if $conn is really a mysqli resource and is available to your file in proper variable scope.
What I'm trying to do, is create a random string, check it against a table, if it already exists, create a new random string and try again, if it doesn't insert it into said table.
My script is based on a script that I was given yesterday, it's all working as planned aside from if(mysql_num_rows($result) == 0), which will automatically return false and execute the else statement. I've tried to change the value to 1 instead of 0, which executes the if statement, regardless of whether it's true or false (e.g. I swap out $authcode = dechex($num1).$dechex($num2); for a string such as $authcode ="eey7y764"; which doesn't exist in the table, yet it still executes the if statement).
Here's my script:
function authCode() {
$num1 = mt_rand(1, 2147483647);
$num2 = mt_rand(1, 2147483647);
$authcode = dechex($num1).dechex($num2);
include("../db/71cfde725dc86.php");
$conn = mysql_connect($db_host, $db_uname, $db_pword) or die("Couldn't connect because ".mysql_error()); mysql_select_db($db_name);
$query = "SELECT COUNT(*) FROM records WHERE valcode='$authcode'";
$result = mysql_query($query) or die("SELECT query failed due to ".mysql_error());
if(mysql_num_rows($result) == 0)
{
$authCode = authCode();
}
else
{
$query2 = "INSERT INTO records (valcode) VALUES ('$authcode')";
$result2 = mysql_query($query2) or die("INSERT query failed due to ".mysql_error());
}
mysql_close($conn);
return $authcode;
}
authCode();
Could you please tell me what changes need to be made to have it function as I'd like?
Any comments or advice will be greatly appreciated :)!
You don't want to compare the number of rows. It's always 1, because you're selecting COUNT(*). It will always give you a single number (hopefully 0 or 1). You have to compare 0 and 1 to the VALUE of that number, not how many of that number there are (which will always be 1).
$row = mysql_fetch_array($result);
if($row['COUNT(*)']==1) ...
Also, you don't want to recursively call authCode(), not like that. You'll possibly make a big stack of open DB connections (not to mention that they'll be opened and closed quickly, which is expensive). You'll probably want to pass along the connection.
function authCode($conn){
...
$authCode = authCode($conn);
}
$conn = mysql_connect( ... );
authCode($conn);
mysql_close($conn);