How do I search with the current time in PHP? - php

I have a MySQL table like this:
| rsid | rsuser | rsintime | rsouttime | rsroom |
| ---- | ------ | ------------------- | ------------------- | ------ |
| 1 | Nick S | 2014-10-14 11:17:34 | 2014-10-14 12:18:06 | 1 |
| 2 | Mike G | 2014-10-15 10:18:38 | 2014-10-15 11:19:00 | 1 |
I want to search with the current time against the in/out times. So, in English, if the room is busy, echo "Busy". If it is available, echo "Room is free until " the next in time.
Here is what I have so far:
<?php
$con=mysqli_connect("008.178.143.7","roomapp","password","roomapp");
$testschedulesql = "SELECT (NOW() > rsintime AND NOW() < rsouttime) as res_rm from raRmSchedule";
$testscheduleqry = mysqli_query($con, $testschedulesql);
$testschedule = mysqli_num_rows($testscheduleqry);
if($testschedule > 0){
echo 'Busy';
}
else{
echo 'Not';
}
?>
This always returns as true.

If you were to solve it in MySQL it could be something like this:
SELECT IF (NOW() > rsintime AND NOW() < rsouttime)
THEN 'Busy'
ELSE
THEN CONCAT('Room is free until ',
(SELECT rsintime
FROM rooms
WHERE rsid <> rsintime
ORDER BY rsintime
LIMIT 0, 1))
AS room_status
WHERE rsid = theIdOfTheRoom
This is just a guide though. I'm not sure if it works because I can't test it now and a better one could probably be written to solve this. But hopefully it can get you rolling.

Related

Get Thread information from Single Database

I am trying to learn how to create a simple forum and i stuck in here;
My Database is something like this; (post table)
ThreadID | PostID | Author | Title | Content | Date | Time
--------------------------------------------------------------
1 | 1 | Jack | Thread 1 | ... | 14/12/2015 | 20:21
1 | 2 | Arn | | ... | 15/12/2015 | 19:28
1 | 3 | Hank | | ... | 15/12/2015 | 20:24
2 | 1 | Tom | Thread 2 | ... | 15/12/2015 | 22:41
2 | 2 | Frank | | ... | 16/12/2015 | 13:06
Post table contains both replies and threads
And i would like to get some information from database on category segment
and this is what i want;
Title | Author | Replies | Views | Last Poster
-------------------------------------------------------------------------
Thread 1 | Jack | 2 | - | Hank - 20:24 15/12/2015
Thread 2 | Tom | 1 | - | Frank - 20:24 15/12/2015
and finally my code is;
$get_threads = "SELECT threadid, title, author, postid, date, time FROM post WHERE categoryid = '" . $category . "'";
$threads = mysqli_query($conn, $get_threads); if (mysqli_num_rows($threads) > 0) {while($row = mysqli_fetch_assoc($threads)) {
$get_reply = "SELECT (MAX(postid)-1) rn, (max(postid)) lp FROM post WHERE threadid = '".$row["threadid"]."'";
$reply = mysqli_query($conn, $get_reply); if (mysqli_num_rows($reply) > 0) {while($rod = mysqli_fetch_assoc($reply)) {
$get_lp = "SELECT op.author, op.date, op.time FROM post op INNER JOIN (SELECT author, date, time FROM post WHERE POSTID = '".$rod["lp"]."' GROUP BY threadid) lp ON op.author = lp.author AND op.date = lp.date AND op.time = lp.time WHERE threadid = '".$row['threadid']."'";
$lp = mysqli_query($conn, $get_lp); if (mysqli_num_rows($lp) > 0) {while($roc = mysqli_fetch_assoc($lp)) {
echo "<div class='thread'><div class='threadbox'>";
echo "<a href='forum.php?post=".$row["threadid"]."'class='ttitle'>".$row["title"]."</a>";
echo "<div class='tauthor'>".$row["author"]."</div>";
echo "<div class='treplies'>".$rod["rn"]."</div>";
echo "<div class='tviews'>".$row["date"]."</div>";
echo "<div class='tlastposter'>".$roc['author']." - ".$roc["time"]." ".$roc["date"]."</div>";
echo "</div></div><div class='threaddiv'></div>";
}}}}}} else {echo "<center>Content Not Found</center>";}
Well it may be the worst code ever written but its my first, i apologize for that anyway its duplicating some results i couldnt figure out.
Please help me about how i can handle it?
If you improove and shorten this code i would be glad ^^
Thanks in Advance

Searching MySQL with Now() always returns true

I have a MySQL table like this:
| rsid | rsuser | rsintime | rsouttime | rsroom |
| ---- | ------- | ---------------- | ---------------- | ------ |
| 1 | Nick S | 10/14/2014 11:17 | 10/14/2014 12:18 | 1 |
| 2 | Mike G | 10/15/2014 10:18 | 10/15/2014 11:19 | 1 |
| 3 | Chuck M | 10/14/2014 21:56 | 10/14/2014 22:56 | 1 |
| 4 | Jake B | 10/26/2014 22:14 | 10/26/2014 23:15 | 1 |
My PHP code is:
<?php
$con=mysqli_connect("0.0.0.0","roomapp","hi","roomapp");
$testschedulesql = "SELECT (NOW() > rsintime AND NOW() < rsouttime) as res_rm from raRmSchedule";
$testscheduleqry = mysqli_query($con, $testschedulesql);
$testschedule = mysqli_num_rows($testscheduleqry);
$testscheduletext = mysqli_fetch_array($testscheduleqry);
echo $testschedule;
if($testschedule > 0){
echo 'Busy';
}
else{
echo 'Not';
}
?>
However, $testschedule always returns the total rows. I want it to return only rows where the current time is within an in/out time. What am I doing wrong?
You need a where clause:
SELECT rm.*
from raRmSchedule
WHERE (NOW() > rsintime AND NOW() < rsouttime)
To count the number of rows:
SELECT COUNT(*)
from raRmSchedule
WHERE (NOW() > rsintime AND NOW() < rsouttime)
This returns one row with one column. It will be 0 if there are no matches.
Your version returns one row for each row in the table. There will be one column with a value of 0 or 1, depending on whether the condition matches.
Of course it will give you all rows, as what you are selecting is the boolean value of an expression.
I think what you want is giving the query a WHERE clause to filter the time you're needing.
Something like
Select * from raRMSchedule where (now() > rsintime and now() < rsouttime).

Is it possible to sort by the duration of time when its computed based on the joined table?

I have a query to get the total number of duration of when the user become internal,hm,rec status. I wanted to ask, is it possible to sort it by total number of duration when it's re calculated from another table? Please see my query structure to understand further.
The user can be assigned into many status. It can be that he was in internal status for 4th times,rc for 2 times and etc.
$sql = "SELECT * FROM user WHERE creation_date < NOW()";
$qry = mysql_query($sql);
$res = array();
while($row=mysql_fetch_assoc($qry))
{
$res[] = $row;
$res['duration'] = getTimeDuration($row['userId'],$row['startDate']);
}
function getTimeDuration($userId,$startDate);
{
$sql = "SELECT statusDate FROM userStatus WHERE userId=$userId AND status IN('internal','hm','rec') ORDER BY statusDate DESC
$qry = mysql_query($sql);
While($row=mysql_fetch_assoc($qry))
{
$diff = $row['statusDate']-$startDate;
$duration = $duration + $diff;
}
return $duration;
}
This is the table structure
user Table
+----------+--------------+
| userId | startDate |
+----------+--------------+
| 1 | 2011-09-18 |
+----------+--------------+
| 2 | 2012-05-25 |
+----------+--------------+
userStatus Table
+----------+--------------+--------------+
| userId | statusDate | status |
+----------+--------------+--------------+
| 1 | 2012-09-18 | internal |
+----------+--------------+--------------+
| 1 | 2012-10-18 | hm |
+----------+--------------+--------------+
| 1 | 2012-10-25 | rec |
+----------+--------------+--------------+
| 1 | 2012-11-05 | manager |
+----------+--------------+--------------+
| 1 | 2012-11-15 | assistant |
+----------+--------------+--------------+
| 1 | 2012-12-05 | internal |
+----------+--------------+--------------+
| 2 | 2012-10-05 | rec |
+----------+--------------+--------------+
| 2 | 2012-11-05 | internal |
+----------+--------------+--------------+
Output:
http://screencast.com/t/BsgouWSc5H3m
In my screenshot, USER ID: 1 had a total time duration all in all for 1589. USER ID: 2 has a duration of 297. What I want is to add the ability to sort base on the total time of duration. In this case, if DESC USER ID 1 will show first. Then, if ASC USER ID: 2 will show first.

Concatenation of date (in date datatype) and time (in time datatype) in PHP

Does concatenation in php make a difference. Lets say I have a time_in column (time datatype) and date_in column (date datatype) in my database.
Example:
id | time_in | time_out | date_in | date_out |
1 | 9:30pm | 7:30am | 2013-12-01 | 2013-13-01 |
And in the table in which I will display it it shows like this;
id | Date & Time Login | Date & Time Logout |
1 | 2013-12-01 9:30pm | 2013-13-01 7:30am |
So far I do this in my script;
echo $row ['date_in' . 'time_in'];
In the table it shows 2013-12-01Array and says that array to string conversion?
How do i do this in small and clean script?
Do I need another query for this?
Do I need to use SELECT CONCAT?
Any suggestions.
Try this :
SELECT CONCAT_WS(' ','date_in','time_in') AS datetime_in, CONCAT_WS(' ','date_out','time_out') AS datetime_out FROM table;
Ref: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat
You can do something like this. Concat two variable as per your need.
For Date & Time Login : $login = $row['date_in']." ".$row['time_in'];
For Date & Time Logout : $logout = $row['date_out']." ".$row['time_out'];
<?PHP
$conn=mysql_connect('localhost','root','') or die(mysql_error());
$db=mysql_select_db(ur_dbname, $conn) or die(mysql_error());
$query="SELECT * FROM ur_table_name";
$result=mysql_query($query) or die(mysql_error());
echo "<table style='text-align:center'; cellpadding='3' cellspacing='5'><th><tr><td>ID</td><td colspan='2'>Time_i</td><td colspan='2'>Date_i</td></tr></th>";
while($row=mysql_fetch_array($result) )
{
$dis="<tr><td>".$row['id']." </td><td>|</td><td> ".$row['time_i']." </td><td>|</td><td> ".$row['date_i']."</td><td>|</td></tr>";
echo $dis;
}
echo "</table>";
?>
i think this may work for you -- adn -- output will be
ID Time_i Date_i
1 | 11:08:40 | 2013-03-06 |
2 | 11:11:46 | 2013-03-06 |
3 | 00:00:00 | 2013-03-06 |
4 | 00:00:00 | 2013-03-06 |
5 | 11:16:40 | 2013-03-06 |
6 | 11:16:54 | 2013-03-06 |
you can try this also
echo $row['id']." | ".$row['time']." | ".$row['date'];

How to speed up my php PSQL query

REQUESTED TABLE DEFINITIONS
Table "public.call_record"
Column | Type | Modifiers
-----------------+------------------------+---------------
cntrct_id | character varying(15) | not null
call_regard | text |
port_type | character varying(9) |
inst | text |
info_taken | character varying(40) |
log_date | date | not null
log_time | time without time zone | not null
act_taken | text |
use_material | text |
targ_pest | integer |
work_comp_by | text |
emp_no | integer |
comp_date | date |
job_start_time | time without time zone |
job_leave_time | time without time zone |
comp_val | boolean | default false
fti_call_regd | public.tsvector |
fti_inst | public.tsvector |
fti_act_take | public.tsvector |
route | character(3) |
act_port | text |
targ_pest_opt | text |
call_regard_opt | text |
targpest_other | text |
date_sched | date |
custord_num | integer |
dist_id | integer |
phone_slot | integer | default 0
Indexes:
"call_record_pkey" PRIMARY KEY, btree (cntrct_id, log_date, log_time)
"route_index" hash (route)
Check constraints:
"call_record_targ_pest_check" CHECK (targ_pest <= 100)
"call_record_targ_pest_check1" CHECK (targ_pest >= 0)
Table "public.per_call"
Column | Type | Modifiers
---------+----------------------+-----------
dist_id | character varying(2) |
route | character varying(2) |
type | character(1) |
total | integer |
I need to get data from 2 tables and print it in a single report. The report should look like this:
district | route | type | total | callbacks
| 01 | T | 12 | 5
| 02 | P | 0 | 0
| 03 | P | 3 | 1
2 | 01 | T | 4 | 1
| 02 | T | 1 | 0
| 03 | P | 0 | 0
etc... (this is theoretical sample data)
So, in essence I need to get the dist_id, route, type, and count(*) from the table per_call
and the count of call_backs from the table call_record
PROBLEM: looping through tables makes it go glacially slow. How can I adjust the following PSQL query so that I don't have to loop and I can echo the tabular data properly?
Let me know if anything is opaque and I will try to clarify
echo '<table align="center" border = 2>
<th>DISTRICT</th>
<th>ROUTE</th>
<th>TYPE</th>
<th>TOTAL</th>
<th>CALL BACKS</th>';
$SQL = " SELECT per_call.dist_id, per_call.route, per_call.type, per_call.total
FROM per_call, call_record
WHERE TRUE ";
if($type == 'termite'){
$SQL = $SQL." AND per_call.type = 'T' ";
}
else{
$SQL = $SQL." AND per_call.type = 'P' ";
}
$SQL = $SQL." AND call_record.dist_id = per_call.dist_id
AND call_record.log_date >= '$startDate'
AND call_record.log_date <= '$endDate'
ORDER BY per_call.dist_id, per_call.route, per_call.type ASC ";
echo $SQL;
/*AND call_record.log_date = '$startDate'
AND call_record.log_date = '$endDate'*/
$Q = pg_query($connect,$SQL);
while($row = pg_fetch_row($Q)){
$dist = $row[0];
$route = $row[1];
$type = $row[2];
$total = $row[3];
echo '<tr>';
echo '<td align="center">'.$dist.'</td>';
echo '<td align="center">'.$route.'</td>';
echo '<td align="center">'.$type.'</td>';
echo '<td align="center">'.$total.'</td>';
$SQL2 = "SELECT COUNT(*)
FROM call_record
WHERE dist_id = $dist
AND route = '$route'
AND substring(cntrct_id from 2 for 1) = '$type'
AND substring(call_regard_opt from 2 for 1) = '1'
";
$Q2 = pg_query($connect,$SQL2);
$row2 = pg_fetch_row($Q2);
$callbacks = $row2[0];
echo '<td align="center">'.$callbacks.'</td>';
echo '</tr>';
}
echo "</table>";
select pc.dist_id, pc.route, pc.type, pc.total,
count(
substring(cntrct_id from 2 for 1) = '$type'
AND substring(call_regard_opt from 2 for 1) = '1'
or null
) callbacks
from
per_call pc
inner join
call_record cr on cr.dist_id = pc.dist_id
where cr.log_date between '$startdate' and cr.log_date <= '$enddate'
group by pc.dist_id, pc.route, pc.type, pc.total
order by pc.dist_id, pc.route, pc.type asc
You don't have any indexes on dist_id in either table, which is going to make your join very slow. Add indexes on dist_id and see how much it improves.
Also, that query inside the loop is going to be the death of you, because you're going to be doing many many many queries. Work the inner query into your main query so you only execute one query in the database.
Unless index problems, your query is not badly written, so it can't be really optimized from a query form point of view. You can do that though which is cleaner :
$SQL = "SELECT per_call.dist_id, per_call.route, per_call.type, per_call.total
FROM per_call, call_record
WHERE call_record.dist_id = per_call.dist_id
AND per_call.type = '".($type == 'termite' ? "T" : "P")."'
AND call_record.log_date >= '$startDate'
AND call_record.log_date <= '$endDate'
ORDER BY per_call.dist_id, per_call.route, per_call.type"
Anyway, this is still vulnerable to SQL injections. Try using parameterized queries.

Categories