Reputation: 3
Any advise or guidance would be greatly appreciated!!
table schedule
ID | stud_id| day | timein | timeout
1 | 8888 | Monday | 08:00AM | 09:00AM
2 | 8888 | Monday | 10:00AM | 12:00PM
3 | 8888 | Monday | 01:00PM | 03:00PM
4 | 8888 | Tuesday| 05:00PM | 07:00PM
php code is given below:
<?php
$query=$conn->query("SELECT * FROM schedule where day = Monday and stud_id = 8888")or die(mysql_error());
$i = 0;
$time = strtotime(date('h:iA'));
while($row = $query->fetchall()){
$count = $query->rowcount();
if($count > 0){
$timein = $row[$i]['timein'];
$timeout = strtotime($row[$i]['timeout']);
}
if($time > $timeout){ //example time is 09:50am
$i++;
$timein;
$timeout;
}
echo $timein, $timeout;
this should be good because it will output the second row, but when the time is 12:50PM it still echo the second row even though it should echo the third row, I know my syntax is not correct, I just dont know how to do this correctly.
Upvotes: 0
Views: 60
Reputation: 446
Your code isn't correct in many ways:
1- $query->fetchAll()
shouldn't be used inside while
condition, instead you have to define a variable which will contain the query result then iterate through it using for
or foreach
. For example, $result = $query->fetchAll();
2- The code inside while
loop will print $timein
and $timeout
no matter what because the conditions you wrote doesn't stop the execution of this line echo $timein, $timeout;
3- Why did you use $query->rowcount()
? It contains the total rows in the result array. So if you want to use it, it has to be before the loop not inside it.
4- These two lines $timein; $timeout;
doesn't perform any logical operation, it has no use here.
Here's a correct approach:
<?php
$query= $conn->query("SELECT * FROM schedule where day = Monday and stud_id = 8888") or die(mysql_error());
$time = strtotime(date('h:iA'));
$result = $query->fetchAll();
foreach($result as $row) {
$timein = $row['timein'];
$timeout = strtotime($row['timeout']);
if ($time > $timeout)
{
continue;
}
else
{
echo $timein;
}
}
Upvotes: 1
Reputation: 308
Maybe the timein, timeout fields should be stored as time in the database (for example "08:00:00" instead of "08:00AM"
Also there was a missing } in the end
This works if you do the change in your database:
<?php
$query=$conn->query("SELECT * FROM schedule where day = Monday and stud_id = 8888")or die(mysql_error());
$i = 0;
$localtime = "12:50:00";
$time = strtotime($localtime);
while($row = $query->fetchall()){
$count = $query->rowcount();
if($count > 0){
$timein = $row[$i]['timein'];
$timeout = strtotime($row[$i]['timeout']);
}
if($time > $timeout){ //example time is 09:50am
$i++;
$timein;
$timeout;
}
}
echo $timein." - ".$timeout."<br/>";
?>
Upvotes: 1