I have a php that extracts information from a mysql database just fine, however when I tried to add the functionality to check for data depending on an interval I am not getting any data from the database, just replies with an empty result. When I run it in Phpmyadmin it works just fine. Here's the code:
$result = mysql_query("
SELECT * FROM SensorLog
WHERE (SensorTag='$requestedSensor' and TimeEntered<'$end'
and TimeEntered>'$start');
") or die(mysql_error());
start and end are of the form: 2014-01-22 15:36:37 just like my timestamped column in the database.
What am I doing wrong here? I assume something is wrong with the query but I can't figure out what.
Same can be achieved using BETWEEN clause as follows:
$result = mysql_query("SELECT * FROM SensorLog
WHERE (SensorTag='$requestedSensor' and TimeEntered BETWEEN '$end' AND '$start')") or die(mysql_error());
If date start and date end have the same value, the query should be TimeEntered >= $start and TimeEntered <= $end
Related
Trying to pull client information from SQL server using PHP and count how many clients signed up last month based on the date they signed up. I want to use DATEPART and DATEADD to specify the parameters I want for grabbing last months information, but the server doesn't seem to recognize these parameters. Currently using MySQL 5.6.44.
I know statements like
SELECT CLIENT_EMAIL
FROM CLIENT_TABLE
AND DATE_CLIENT_ADDED > (CURRENT_DATE() - INTERVAL 30 DAY)
works, but this is very limiting
$con = mysqli_connect($Host, $User, $Password, $DB);
$getLastMonthEnrollments = "SELECT CLIENT_EMAIL FROM CLIENT_TABLE AND DATEPART(m, DATE_CLIENT_ADDED) = DATEPART(m, DATEADD(m, -1, getdate()))";
$tempQuery = mysqli_query($con, $getLastMonthEnrollments);
$LastMonthEnrollments = mysqli_num_rows($tempQuery);
I expect to get a number from counting the rows, but my result is null. When I attempt to run this within the server itself, I get
FUNCTION my_DB.DATEPART does not exist
Am I doing this wrong? I've read many documentations and questions on here and this seems to be the correct usage.
You are using SQL Server syntax from your Laravel code, yet the underlying database is MySQL. Here is your query, rewritten and also corrected:
SELECT CLIENT_EMAIL
FROM CLIENT_TABLE
WHERE MONTH(DATE_CLIENT_ADDED) = MONTH(CURDATE() - INTERVAL 1 MONTH);
I'm using PHP to send this query where lastConn is a datetime object.
$result = $mysqli->query("SELECT id, username, lastConn FROM users LIMIT $startIndex, 50") or die($mysqli->error);
However my goal is not to get the raw lastConn data, but the time difference between lastConn and CURRENT_TIMESTAMP. I wrote this query which does the job :
SELECT TIMESTAMPDIFF(MINUTE,lastConn,CURRENT_TIMESTAMP) AS 'duration' FROM users;
I'm now trying to merge these two queries together to get the time difference in the first query but I can't seem to find the correct syntax.
Here is how I'm retrieving the data after performing the query using PHP:
while($row = $result->fetch_assoc()){
echo $row['id'];
echo $row['username'];
echo $row['lastConn']; //should echo the time difference instead of the raw lastConn value
}
How can I directly get the time difference between lastConn and CURRENT_TIMESTAMP in my first query, without having to use a second one ?
you could probably just add the portion of your second query to the first, like this below. you had it all working, just needed that last step!
$mysqli->query("SELECT id, username, lastConn, TIMESTAMPDIFF(MINUTE,lastConn,CURRENT_TIMESTAMP) AS 'duration' FROM users LIMIT $startIndex, 50")
hope this helps.
I am working on a project in which the dates in the sql table needs to be checked with current date. If the ticket goes past the current date, then the status of ticket go from Active to Expired.
I am not good at php. This is what I came up with. I wrote this function at top of the page so that each time the page loads, it checks for the date and compares. date format is yyyy-mm-dd.
What am I doing wrong. Can anyone please help me out?
$result= "SELECT date, status FROM TABLE1";
while($row = sqlsrv_fetch_array($result)){
if(strtotime($row['date']) > strtotime(date('Y-m-d'))){
$updatequery = " UPDATE TABLE1 SET $row[status] = 'Expired' ";
}}
I would advise using the PHP DateTime class it has the date diff function so you could implement like this
$today = new DateTime('today');
$expires = new DateTime($datefromdb);
$diff = $today->diff($expires);
if($diff < 1)
{
$updatequery = " UPDATE TABLE1 SET $row[status] = 'Expired' ";
}
You can use
$result= "SELECT UNIX_TIMESTAMP(date) AS unixdate, status FROM TABLE1";
and then compare
if ($row['unixdate']) > strtotime(date('Y-m-d')))
Your sql database may be on a server whose time is different from the time on the machine where you are running the code, so I would recommend doing the check and update all on the sql server side.
(Disclaimer: I use mysql, so that's how I've written my answer. I assume you can translate to whatever sql database you use)
I would recommend using MySql's date functions, which you can see here.
UPDATE TABLE1 SET status='Expired' WHERE DATEDIFF(CURDATE(), date) < 0
Below code working for me, just a single line of update query will updated less than of current date
UPDATE TABLE_NAME SET status='expired' WHERE DATEDIFF(date, CURDATE()) < 0
Thank.
I have my SQL statement like this trying to get the difference in 2 timestamps greater than 10 minutes. "timestamp" is a column in MYSQL which I hold a timstamp as such "1365793346"
SELECT * FROM table WHERE TIMESTAMPDIFF(MINUTE,timestamp,NOW()) AS thisisit
Im not sure if using "AS thisisit" is a current function of TIMESTAMPDIFF but I was able to find some old posts that how it used as such. I am not sure if its supported anymore because I an a syntax error at "AS thisisit"
I have also tried using
SELECT * FROM table WHERE TIMESTAMPDIFF(MINUTE,timestamp,NOW()) > 10
Where I am not sure what is going on is first is my syntax correct and second how to do associate this query with a label so I can echo it. My full PhP code looks like this
SELECT * FROM table WHERE TIMESTAMPDIFF(MINUTE,timestamp,NOW()) > 10
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo $row[0];
}
I was assuming I could use something like this to echo the results, but I get nothing to the screen. Can anyone point me in the right direction?
echo $row[0];
AS thisisit in this case have to be used to set an alias to your column.
So, you should use the following:
SELECT timestamp AS 'thisisit'
FROM table
WHERE TIMESTAMPDIFF(MINUTE, timestamp, NOW()) > 10;
I have this piece of code to check if a user has already created an account the last hour:
$result = mysql_query("SELECT * FROM accounts WHERE registration_ip = '$_SERVER[REMOTE_ADDR]' AND created > ".(time() - 3600));
if (mysql_num_rows($result) > 0)
exit('Blablal')
It does not exit as I want it do, i can make how many accounts i want.
You see any obivious problem? My db tablesandfields are correct
Your problem is probably this, $_SERVER[REMOTE_ADDR]
You are embedding that directly into a double-quoted string. When you want to access an array in a double-quoted string you need to put the variable array access inside a pair of curly braces.
Corrected string:
"SELECT * FROM accounts WHERE registration_ip = '{$_SERVER['REMOTE_ADDR']}' AND created > ".(time() - 3600)
Also, alway quote indexes, you used REMOTE_ADDR instead of 'REMOTE_ADDR' or "REMOTE_ADDR"
Hope this helps.
i just took the spaces out works fine now
registration_ip='$_SERVER[REMOTE_ADDR]'
Test it by removing the registration_ip = '$_SERVER[REMOTE_ADDR]' clause.
Also your sql query AND created > ".(time() - 3600)); is not correct to get the last hour.
You want something like this:
SELECT ... WHERE ...
AND created > DATE_SUB(now(), INTERVAL 1 HOUR)
I tested this locally and for me, it behaves as expected. I would say that the problem is not in your query, but somewhere else. Check your data and make sure it is being inserted as expected.
Also, you might want to use SELECT COUNT to count the columns instead of SELECT * - it should be faster.
$result = mysql_query("SELECT COUNT(*) FROM accounts WHERE registration_ip = '$_SERVER[REMOTE_ADDR]' AND created > ".(time() - 3600));
$count = mysql_fetch_array($result);
if ($count[0] > 0) exit('BLAH');
Yada's answer is correct. The only other comment I would make is that you escape $_SERVER[REMOTE_ADDR] using mysql_real_escape to protect against a SQL inject in the off chance that the variable gets overridden
You need to do use { } around the things that you are embedding into the SQL that are PHP. I think this should work. I always do this as I have found it saves me time debugging as it seems to pop up somewhat frequently.
$result = mysql_query("SELECT COUNT(*) FROM accounts WHERE registration_ip = '{$_SERVER[REMOTE_ADDR]}' AND created > ".({time()} - 3600));
If this doesn't work, save your query into a variable, echo it to the page to see what it is sending.
$sql = "SELECT COUNT(*) FROM accounts WHERE registration_ip = '{$_SERVER[REMOTE_ADDR]}' AND created > ".({time()} - 3600)";
echo $sql;