Merge two SQL queries together (syntax issue) - php

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.

Related

Using two values from different table as date range in query

I have the following code:
<?php
$result = $db->query("select sum(hol_count) as TOTALBOOKEDHOLIDAYS from holidays");
$row = $result->fetch_row();
echo $row[0];
?>
This does a count of hol_count and returns the calculated figure. I have a separate table called 'config' and two columns: 'hol_year_start' and 'hol_year_end' which will set the date range. I am trying include these two values in the query but have encounter a number of errors while trying a number of different ways to achieve this. I have tried to define the two values as variables and then use those variables with BETWEEN to do the count between the who date ranges. I keep getting an error regarding $row = $result->fetch_row(); as well as trying the following:
("select sum(hol_count) as TOTALBOOKEDHOLIDAYS from holidays
BETWEEN
(SELECT hol_year_start FROM config)
AND
(SELECT hol_year_end FROM config) )"
I know this is probably something very simple but I just cant seem to define the two values as variables then use them in the query to retrieve the required data.
What would be the correct way to define the two values from the config table then use them in the query to count hol_count from the holiday table?
You look you are missing the WHERE in you query. Also the subselects must return only one result. In case you are using MySQL, you would need to set LIMIT 1.
SELECT SUM(hol_count) AS TOTALBOOKEDHOLIDAYS FROM holidays
WHERE date_field_name
BETWEEN (SELECT hol_year_start FROM config LIMIT 1)
AND (SELECT hol_year_end FROM config LIMIT 1)

how to get the last value from mysql and increment with php

i have a user database and i have to assign a user id for them for example AA01
AND after insert 1 person into database i have to insert another person with user id AA02 AND i have increment it and so on.
what i have already tried is
$sql_user_id=mysql_query("SELECT MAX(user_id) FROM `users` desc LIMIT 1");
$new_array = explode('AA',$sql_user_id);
$number=$new_array[1];
$newnumber=$number+1;
and i am getting wrong with result Resource id #5
You have to fetch the query results before you can use them.
$result=mysql_query("SELECT MAX(user_id) AS maxId FROM `users` desc LIMIT 1");
$sql_user_id = mysql_fetch_assoc($result);
$new_array = explode('AA',$sql_user_id['maxId']);
$number=$new_array[1];
$newnumber=$number+1;
FYI, I added an alias to your query as it makes referencing a value returned from a function much easier to do.
mysql_query() returns a resource, not a value you can operate directly. You have to fetch the value from this resource first:
$res = mysql_query('SELECT MAX(`user_id`) FROM `users`');
$val = mysql_fetch_row($res);
$new_array = explode('AA', $val[0]);
...
Also, notice that MAX() causes an implicit grouping to happen. So there is no order, and there is only one result. Specifying any of this in your query is futile.
In addition, notice that, since user_id is aparently a text, it might not work as expected. When sorting text, 2 comes after 10. You may need to use a different reference to fetch the latest user_id. If you can help it, don't use text to index your records.

PHP Mysql Query with Time Interval

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

Getting minute difference between two timestamps in mysql using TIMESTAMPDIFF

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;

Php - Mysql. Get players into an array and sort by time

I'm trying to create an array, and then sort the objects by time, from a mysql_query.
This is what happens:
When a player has completed his turn, I update the database. I set the database variable "lastTurn" to the current time.
$nickname = $_POST['name'];
$lastTurn = date();
$myTurn = NO;
$query ... update query
Now I need to find out who the next player is, and send the turn to him/her.
$query = "SELECT * FROM active_users_table WHERE match_id='12345'
This gives me all the player associated with the current game.
But now I don't know how to continue.
I want to put all the players into an array, and then sort it after turnDate i guess, to see who the next player is. Like a poker game. I also need to check another variable in the database, "havePlayerLost", to see if he still is active in the game. If he have lost, then get the next player who is active, and with the highest turnDate.
Any advice is very appreciated.
Thanks
I would suggest you let MySQL/SQL do a little more work than you're doing right now. The SQL query you use to update the player, can also contain the current date / time in the right format.
player_lastTurn = NOW()
When it comes to sorting your array, I'd suggest you let MySQL handle this one aswell:
ORDER BY player_lastTurn ASC
ASCending means it will give you the oldest DateTime for that cellname within the entire database.
When you use the results of these queries and build your array using it, you're array will automatically be in the correct order.
The same applies for the "lost players", so you automatically not include them in the array when you're not loading it.
To get the player sorted try to change the query adding ' ORDER BY turnDate ASC '
$query = "SELECT * FROM active_users_table WHERE match_id='12345' ORDER BY turnDate ASC"
For the variable "havePlayerLost" I think you can change the query too like this adding ' havePlayerLost = false '
$query = "SELECT * FROM active_users_table WHERE match_id='12345' AND havePlayerLost = false ORDER BY turnDate ASC"
try this query
$query = "SELECT * FROM active_users_table WHERE match_id='12345'
and status !='havePlayerLost'
order by lastTurn Asc

Categories