Why isn't php subtracting $ltimeout from $ltimein? It just returns $ltimein. Here's my code:
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$querytimein = mysql_query("
SELECT timein
FROM studentInfo
WHERE name = '$name'
ORDER BY time DESC
LIMIT 1
")
or die("Error querying database ".mysql_error());
$querytimeout = mysql_query("
SELECT timeout
FROM studentInfo
WHERE name = '$name'
ORDER BY time DESC
LIMIT 1
")
or die("Error querying database ".mysql_error());
while($minutestimein = mysql_fetch_array($querytimein)){
$ltimein = $minutestimein['timein'];
}
while($minutestimeout = mysql_fetch_array($querytimeout)){
$ltimeout = $minutestimeout['timeout'];
}
$timegone = $ltimein - $ltimeout;
echo $timegone;
}
BTW I know I need to switch to mySQLi, I will do that before I publish my website.
Since you are retrieving only a single row use
$ltimein = mysql_fetch_row($querytimein);
$ltimeout = mysql_fetch_row($querytimeout);
And then you could find the difference like this:
if(isset($ltimein) && isset($ltimeout)){
$timediff = strtotime($ltimein['timein'])- strtotime($ltimeout['timeout']);
}
you can also do the time difference in mysql query:
select UNIX_TIMESTAMP(timein) - UNIX_TIMESTAMP(timeout) as time_diff from studentInfo where '$name' ORDER BY time DESC LIMIT 1
Related
I have a sql query which has an if..else function. if the submit button is clicked, it will perform the particular query. else, the query will take in the first 20 dates in my database. however, i am not sure how to do the else query statement to take up only the first 20 dates. do help, thank you :)
<?php
$server = "localhost";
$user = "root";
$password = "";
$database = "sensors_database";
$connection = mysql_connect($server,$user,$password);
$db = mysql_select_db($database,$connection);
if(isset($_POST["usub"])){
$date1 = $_POST["datepicker"];
$date2 = $_POST["datepicker1"];
$query1 = "SELECT time, Ultrasonic FROM pi_sensors_network WHERE date BETWEEN '".$date1."' AND '".$date2."'";
$result1 = mysql_query($query1);
while($row = mysql_fetch_assoc($result1))
{
$dataset1[] = array(strtotime($row['time'])*1000,$row['Ultrasonic']);
//echo strtotime($row['time'])*1000;
}
}
else {
}
?>
Here you go:
SELECT `time`, `Ultrasonic` FROM `pi_sensors_network`
WHERE 1=1 ORDER BY `date` ASC LIMIT 0,20
If you are asking between the dates you mentioned in the query, then use
limit
$query1 = "SELECT time, Ultrasonic FROM pi_sensors_network WHERE date BETWEEN '".$date1."' AND '".$date2."' limit 0,20";
First Create index on table < pi_sensors_network > on column < date >
CREATE INDEX pi_sensors_network01 ON pi_sensors_network (`date`);
Then,
SELECT
`time`,`Ultrasonic`
FROM
pi_sensors_network
WHERE
`date` IN ( SELECT `date` FROM
(SELECT DISTINCT(`date`)
FROM pi_sensors_network
ORDER BY `date` ASC LIMIT 0,20)
AS tmp ) ;
If your table is too large, This query may take long even after indexing,
In this case,
I'ld suggest you to make an array of first 20 dates by separate query and then implode it in your main query !
I'm trying to sort this query by time.
I have a gaming match system. And I want to get a list of next 5 matches from my local time zone.
<?php
include_once "include/dbcompo.php";
$q=mysqli_query($con, "SELECT * FROM kamper ORDER BY tid LIMIT 5");
while($row = mysqli_fetch_array($q))
{
$clan1 = $row['clan1'];
$clan2 = $row['clan2'];
$server = $row['server'];
$tid = $row['tid'];
echo $clan1." ".$clan2." ".$server." ".$tid;
echo "<br />";
}
?>
Add a WHERE clause in your query: WHERE tid > NOW().
With NOW() you take the time of the server, maybe you should replace it with new DateTime(null)->getTimestamp()
Something like that:
<?php
mysqli_query($con, 'SELECT * FROM kamper WHERE tid > NOW() ORDER BY tid LIMIT 5');
// or
mysqli_query($con, 'SELECT * FROM kamper WHERE tid > '.new DateTime(null)->getTimestamp().' ORDER BY tid LIMIT 5');
?>
Two options:
1st option: Make the time field a numeric field and sort in PHP:
$queryResult = mysqli_query($con, $query);
while($row = mysqli_fetch_array($queryResult) {
$oldArray[$row['time'] = $row;
}
$array = ksort($oldArray);
foreach($array as $time=>$row) {
// do something
}
2nd option: Make a subquery
SELECT * FROM (
SELECT * FROM kamper WHERE timezone = 'UTC' ORDER BY tid
) LIMIT 5
Im trying to do a mysql check if a record from $uid exist from today based on $timestamp and if it doesnt then do an INSERT.
//EXAMPLE RECORD FROM TABLE VOTE
--- #vote_fb_uid# --- #vote_time#
665414807 1369219044
tjt
//STEP 1 - do a look up on $uid and check with timestamp $today
$timestamp = $this->time;
$date = date('Y-m-d', $timestamp);
$today = date('Y-m-d');
$sql = "
SELECT * FROM vote WHERE
vote_fb_uid = '$this->fb_uid',
WHERE vote_time = '$CHECK_IF_THERE_IS_AN_ENTRY_FROM_TODAY'";
$res = mysql_query($sql) or die( mysql_error());
//STEP 2 - If no records are found for today - then we do an INSERT
if($no_record_for_today) {
$sql = sprintf("
INSERT INTO vote(
vote_fb_uid,
vote_time)
VALUES ('%s','%s')",
mysql_real_escape_string($this->fb_uid),
mysql_real_escape_string($this->time));
$res = mysql_query($sql) or die( mysql_error());
}
Obviously im strugling with the SQL part for the look up - im wondering if there isnt some in-built SQL function to do this or similar?
to check if you had a vote in the last 24 hours :
SELECT *
FROM vote
WHERE vote_fb_uid = '$this->fb_uid'
AND FROM_UNIXTIME(vote_time) >= DATE_SUB(NOW(), INTERVAL 1 DAY)
if you want to limit to the same day (mean you are allowed to post at 2013.05.21 23:55 and 2013.05.22 00:05)
SELECT *
FROM vote
WHERE vote_fb_uid = '$this->fb_uid'
AND DATE(FROM_UNIXTIME(vote_time)) = DATE(NOW())
CURDATE()
Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context.
mysql> SELECT CURDATE();
-> '2008-06-13'
mysql> SELECT CURDATE() + 0;
-> 20080613
Try this:
$today = date('Y-m-d'); //change it to timestamp if you want in timestamp
$sql = "
SELECT count(*) as total FROM vote WHERE
vote_fb_uid = '$this->fb_uid' and
vote_time = '$today'";
$res = mysql_query($sql) or die( mysql_error());
if($res[0]['total'] < 1){
$sql = sprintf("
INSERT INTO vote(
vote_fb_uid,
vote_time)
VALUES ('%s','%s')",
mysql_real_escape_string($this->fb_uid),
mysql_real_escape_string($this->time));
$res = mysql_query($sql) or die( mysql_error());
} else{
//return error("custom","","Already Inserted.");
echo "already inserted";
}
Your $sql query have a syntax error, you have used two times clause WHERE the correct syntax to use two or more clauses in where is using AND to join them, to get only record wich don't have an entry for today you can use DATE_SUB with 1 day interval
SELECT *
FROM vote
WHERE vote_fb_uid = '$this->fb_uid',
AND vote_time <= DATE_SUB(vote_time, INTERVAL 1 DAY)
My page displays an image, and I want to display the previous and next image that is relevant to the current one. At the moment I run the same query 3x and modify the "where" statement with =, >, <.
It works but I feel there must be a better way to do this.
The image id's are not 1,2,3,4,5. and could be 1,2,10,20,21 etc. But if it is much more efficient I am willing to change this.
mysql_select_db("database", $conPro);
$currentid = mysql_real_escape_string($_GET['currentid']);
$query ="SELECT * FROM database WHERE id ='".$currentid."' LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$current_id = $row['id'];
$current_header = $row['title'];
$current_description =$row['desc'];
$current_image = "http://".$row['img'];
$current_url = "http://".$row['id']."/".$db_title."/";
$current_thumb = "http://".$row['cloud'];
}
mysql_select_db("database", $conPro);
$query ="SELECT * FROM database WHERE id <'".$currentid."' ORDER BY id DESC LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$previous_id = $row['id'];
$previous_header = $row['title'];
$previous_description =$row['desc'];
$previous_image = "http://".$row['img'];
$previous_url = "http://".$row['id']."/".$db_title."/";
$previous_thumb = "http://".$row['cloud'];
}else{
$previous_none = "true"; //no rows found
}
mysql_select_db("database", $conPro);
$query ="SELECT * FROM database WHERE id >'".$currentid."' ORDER BY id ASC LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$next_id = $row['id'];
$next_header = $row['title'];
$next_description =$row['desc'];
$next_image = "http://".$row['img'];
$next_url = "http://".$row['id']."/".$db_title."/";
$next_thumb = "http://".$row['cloud'];
}else{
$next_none = "true"; //no rows found
}
mysql_close($conPro);
Thank you for your time
You don't have to do select_db each time. Once you 'select' a db, it stays selected until you select something else.
You can't really get away from doing two separate queries to get the next/previous images, but you can fake it by using a union query:
(SELECT 'next' AS position, ...
FROM yourtable
WHERE (id > $currentid)
ORDER BY id ASC
LIMIT 1)
UNION
(SELECT 'prev' AS position, ...
FROM yourtable
WHERE (id < $currentid)
ORDER BY id DESC
LIMIT 1)
This would return two rows, containing a pseudofield named 'position' which will allow you to easily identify which row is the 'next' record, and which is the 'previous' one. Note that the brackets are required so that the 'order by' clauses apply to the individual queries. Without, mysql will take the order by clause from the last query in the union sequence and apply it to the full union results.
You can get the "previous" one first WHERE id <'".$currentid."' ORDER BY id DESC, and then query for two "above" it: SELECT * FROM database WHERE id >= '".$currentid."' ORDER BY id ASC then it takes only two queries instead of three.
I have the following PHP functions that determine the next and previous rows in a database. However, there are lots of occasions when rows can be deleted and therefore my functions will not work as all they do is decrement the auto_increment field.
For example, current row 5. My function gives: 4 (previous) and 6 (next). What if 6 and 7 is deleted. My best idea is to keep querying until I get a row, but this seems inefficient, is there a better way?
Thanks all
//function to get next tweet
function getNextTweet($key, $direction){
$sql = "SELECT tweet_id FROM tweets WHERE tweet_key = '$key' LIMIT 1";
$result = mysql_query($sql) or die("DB Error : ". mysql_error());
$result = mysql_fetch_assoc($result);
if($direction=='next'){
$tweet_id = $result['tweet_id'] + 1;
}else{
$tweet_id = $result['tweet_id'] - 1;
}
$sql = "SELECT * FROM tweets WHERE tweet_id = '$tweet_id' LIMIT 1";
$result = mysql_query($sql) or die("DB Error : ". mysql_error());
return mysql_fetch_assoc($result);
}
Assuming you don't have a bajillion records...
Previous:
SELECT *
FROM table
WHERE (id < currentID)
ORDER BY id DESC
LIMIT 1
Next
SELECT *
FROM table
WHERE (id > currentID)
ORDER BY id ASC
LIMIT 1
If you run a modern version of MySQL, you can simplify your function into
function getNextTweet($key, $direction)
{
$cmp = ($direction == 'next') ? '>' : '<';
$order = ($direction == 'next') ? 'ASC' : 'DESC';
$sql = "SELECT *
FROM tweets
WHERE tweet_id $cmp (SELECT tweet_id FROM tweets WHERE tweet_key = '$key' LIMIT 1)
ORDER BY tweet_id $order
LIMIT 1";
$result = mysql_query($sql) or die("DB Error : ". mysql_error());
return mysql_fetch_assoc($result);
}
As long as "tweet_id" is indexed, the query will be very fast, even for millions of records.
One last thing, make sure that $key is properly validated! Otherwise, anyone can inject SQL in your query, that's a huge security flaw. If $key is anything but a hash key, it should at least go through mysql_real_escape_string()