Identifying time in & time out in a column - php

I have a Library system for time in & out for the students. The students can go in when they want and go out when they want. This is how it works: There is a barcode on each student ID. They need to hover under the scanner every-time they pass the door, which automatically saves the Data.
Here is my code for saving.
<?php
$scan=$_GET["scan"];
include("connection/mysqlconnect.php");
$sql="SELECT * FROM student where Barcode like('$scan%')";
$result = $conn->query($sql);
$count=mysqli_num_rows($result);
if($count==1)
{
while($row = mysqli_fetch_array($result)) {
$id = $row['ID'];
$crs_id = $row['course_id'];
}
$my_date = date("Y-m-d h:i:s", strtotime("+7 hours"));
$sql="insert into dtr
(students_id,course_id,Date_Time)values('$id','$crs_id','$my_date')";
$result = $conn->query($sql) or die(mysqli_error());
mysqli_close($conn);
}
?>
The above code works perfectly.
But, I want to identify if it is in or out in a single column.
Below is my sample table. I want to add the In-Out Column.
Student_ID Course_ID Date_Time In-Out
11 4 2018-02-09 08:31:05 in
22 5 2018-02-09 09:35:09 in
22 5 2018-02-09 09:45:08 out
11 4 2018-02-09 10:01:05 out
22 5 2018-02-09 11:35:09 in
My problem is: I want to identify if the last hover is "in", in the column "In-Out" and the system will save the "out".

The simple way would be to select the records from the dtr table for that student/course combination and just fetch the last one...
$sql="SELECT `In-out` as lastAccess FROM `dtr` where Student_ID = $id
order by Date_Time desc limit 1";
$result2 = $conn->query($sql);
$count2=mysqli_num_rows($result2);
$lastAccess = 'out';
if( $count2 == 1 ) {
$row = mysqli_fetch_assoc($result2);
$lastAccess = $row['lastAccess'];
}
$lastAccess = ( $lastAccess == 'out' )? 'in':'out';
This will go after the first SQL to check the student and before the insert. The insert can then use $lastAccess.
Note that if a row in this table isn't found, the value of $lastAccess is 'out' (set prior to the test and therefore the bit which inverts this will set a new value of 'in' as it's the first time this student has used the system.

Here #Nigel
<?php
$scan=$_GET["scan"];
include("connection/mysqlconnect.php");
$sql="SELECT * FROM student where Barcode like('$scan%')";
$result = $conn->query($sql);
$count=mysqli_num_rows($result);
if($count==1)
{
while($row = mysqli_fetch_array($result)) {
$id = $row['ID'];
$crs_id = $row['course_id'];
}
$my_date = date("Y-m-d h:i:s", strtotime("+7 hours"));
$sql="SELECT `in-out` as lastAccess
FROM `dtr`
where student_id = $id
order by Date_Time desc
limit 1";
$result2 = $conn->query($sql);
$count2=mysqli_num_rows($result2);
$lastAccess = 'out';
if( $count2 == 1 ) {
$row = mysqli_fetch_assoc($result2);
$lastAccess = $row['lastAccess'];
// Check
echo "in-out=".$lastAccess.PHP_EOL;
}
$lastAccess = ( $lastAccess == 'out' )? 'in':'out';
// Check
echo "next in-out=".$lastAccess.PHP_EOL;
$sql="insert into dtr (students_id,course_id,Date_Time,in-out)values('$id','$crs_id','$my_date','$lastAccess')";
$result = $conn->query($sql) or die(mysqli_error($conn));
mysqli_close($conn);
}
?>

Related

Expiry date IF santance is not working with MYSQL UPDATE

I have table with many rows. I have exp date and I want to change status of those rows where date is already exp.
It work well if I do not use UPDATE. If I just echo them. But when I want to UPDATE status of this row to 0, problems start. My problem is that it change only 1 row and not all of them that needs to be whit status 0.
$sql = "SELECT * FROM table";
$result = mysqli_query($conn, $sql);
$resultcheck = mysqli_num_rows($result);
$id = $row['id'];
if($resultcheck > 0) {
while($row = mysqli_fetch_assoc($result)) {
$expdate = $row['date'];
$exp = strtotime($date);
$today = date('m/d/Y');
$td = strtotime($today);
if($td>$exp) {
$status=0;
$sql = " UPDATE table SET status = '$status' WHERE ID = '$id' ";
$result = mysqli_query($conn, $sql);
}
}
}
Any advice how to fix that, I tried several option but nothing worked.
Use row['id'] instead of $id.
$sql = " UPDATE table SET status = '$status' WHERE ID = 'row['id']' ";
Rename $result for update. You are reusing the same variable name, hence, after a success update, it will set $result to true and the while loop will stop.

How to LOOP a SELECT query until it finds a data on database (PHP to MySQL)

I wanted to select a row in the database, but if row is not in the database, it should loop until it finds the
This line
$prev_date = date('M d, Y', strtotime($macrodate .' -1 day')); transforms the currentdate to one down (lets say Jun 15, it will transform to Jun 14). And use that date to check if the date is in the database, it not, it will loop and go to Jun 13. Until it could find the date.
How do I do this? What loop should I use?
$query = "SELECT * FROM users_macros WHERE userid = '$userid' AND `date` = '$macrodate'";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) == 0) {
while(1) {
$prev_date = date('M d, Y', strtotime($macrodate .' -1 day'));
$query2 = "SELECT * FROM users_macros WHERE userid = '$userid' AND `date` = '$prev_date'";
$result2 = mysqli_query($con, $query2);
if (mysqli_num_rows($result2) != 0) {
$row2 = mysqli_fetch_assoc($result2);
$targetcarbs = $row2['carbs'];
$targetproteins = $row2['proteins'];
$targetfats = $row2['fats'];
$con->query("INSERT INTO users_macros VALUES('','$userid','$targetproteins','$targetfats','$targetcarbs','$macrodate')");
break;
}
}
}
Don't use a loop. Just use a query that returns the row with the highest date lower than $macrodate. And you can combine that with the INSERT query.
And add a NOT EXISTS criteria to make it select nothing if the given date is already in the table.
Also, use a prepared statement to prevent SQL injection.
$stmt = mysqli_prepare($con, "
INSERT INTO users_macros
SELECT '', userid, proteins, fats, carbs, ? FROM users_macros
FROM users_macros
WHERE userid = ? AND date < ?
AND NOT EXISTS (
SELECT 1 FROM users_macros
WHERE userid = ? AND date = ?
)
ORDER BY date DESC
LIMIT 1");
mysqli_stmt_bind_param($stmt, "sss", $macrodate, $userid, $macrodate, $userid, $macrodate);
mysqli_stmt_execute($stmt);

how to find the particular date data or next date data in mysql database?

I am trying to find the particular date data from database,
my concept is if 2018-11-30 is given to find in database if the date is present in database it should display the date in output, if not present it should add +1 date to 2018-11-30 and try to find the next date 2018-12-01 like wise it goes on.
but i am facing the problem the date is not checked in the database.i am not sure weather my code is correct or wrong can any one give me solution for it.
this is my code
$Firstdate = '2018-11-29';
$Lastdate = '2018-12-03';
$Sql2 = "SELECT ScheduleDate FROM `empdet`";
$result2 = mysqli_query($con, $Sql2);
while($row = mysqli_fetch_array($result2))
{
if($row["ScheduleDate"]==$Firstdate)
{
$DBfirstdate==$Firstdate;
echo "$DBfirstdatebb",$DBfirstdate;
break;
}
else {
$checkFDBdate=date('Y-m-d', strtotime("+1 day", strtotime($Firstdate)));
if($row["ScheduleDate"]==$checkFDBdate)
{
$DBfirstdate=$checkFDBdate;
echo "$DBfirstdate",$DBfirstdate;
break;
}
}
}
$Sql3 = "SELECT ScheduleDate FROM `empdet`";
$result3 = mysqli_query($con, $Sql3);
while($row = mysqli_fetch_array($result3))
{
if($row["ScheduleDate"] == $Lastdate) {
$DBlastdate==$Lastdate;
echo "$DBlastdateBB",$DBlastdate;
break;
}
else {
$checkLDBdate=date('Y-m-d', strtotime("-1 day", strtotime($Lastdate)));
if($row["ScheduleDate"]==$checkLDBdate)
{
$DBlastdate=$checkLDBdate;
echo "$DBlastdate",$DBlastdate;
break;
}
}
}
$sql ="select * from empdet where ScheduleDate between '".$DBfirstdate."' and '".$DBlastdate."'";
$result = $con->query($sql);
SELECT ScheduleDate FROM `empdet` where ScheduleDate > '$Firstdate' and ScheduleDate < '$Lastdate' order by ScheduleDate limit 1
Try this way. You will get the first raw from the date range given.
Select stuff from somewhere where something > 'value' order by something limit 1

Approach and Algorithm for checking availability for schedule using PHPmyadmin and SQL

UPDATED
I'm trying to create a basic schedule for all students in their final year to present their final project to 2 supervisors. I have successfully created a schedule with no constraints but now i need to create a schedule based on the supervisors availability.
Here is a detailed description of the problem.
A student is assigned a supervisor and a supervisor will supervise more than one student. The supervisor also teaches classes during the day. Now i need to create a schedule for all of the students to present to their supervisor and one additional supervisor that supervises other students. (for the moment I'm focusing on the supervisors that are assigned to the student and not the second one until i get it working.
I want to compare the supervisors availability for the slots time if they're free then assign them to the slot and then update the availability of that time to false to avoid double booking using a PHP sql query.
so...
What i have done so far:
// get all of the Slots.
$sql = "SELECT Slot_ID FROM slot WHERE StartTime < '18:00:00'";
$result = mysqli_query($con, $sql);
$DayTimeSlots = array();
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$DayTimeSlots [] = $row;
}
}
// Store slots into simple array
function extractSlotId($DayTimeSlots){
return $DayTimeSlots['Slot_ID'];
}
$slots = array_map("extractSlotId",$DayTimeSlots);
// SHOW SLOTS
foreach ($slots as $slotID) {
echo " SlotID: = $slotID <br>";
}
// Get All students
$sql = "SELECT Student_ID FROM student WHERE PartTime =0";
$result = mysqli_query($con, $sql);
$FullTimeStudents = array();
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$FullTimeStudents [] = $row;
}
}
// Store into a simple array
// Extract student id and Supervisor_ID
function extractStudentId($FullTimeStudents){
return $FullTimeStudents['Student_ID'];
}
$students = array_map("extractStudentId",$FullTimeStudents);
// Combine the Slot and Students array
$min = min(count($FullTimeStudents), count($DayTimeSlots));
$result = array_combine(array_slice($students , 0, $min), array_slice($slots, 0, $min));
foreach($result as $key=>$value){ // $Key = Student_ID, $value = Slot_ID
echo " $key : $value ";
// get supervisor ID
$sql = "select Supervisor_ID FROM student where Student_ID = $key";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_array($query);
$SuperID = $row['Supervisor_ID'];
echo "SuperID : $SuperID ";
// get slotID
$sql = "select Date, StartTime FROM Slot where Slot_ID = $value";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_array($query);
$Date = $row['Date'];
$StartTime = $row['StartTime'];
echo "Slot Date : $Date Start Time : $StartTime ";
// get Date id
$sql = "select Date_ID FROM dates where Date = '$Date'";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_array($query);
$DateID = $row['Date_ID'];
echo "Date ID : $DateID ";
// Check if the supervisor is available
$sql = "select `$StartTime` FROM supervisor_availability where Date_ID = $DateID AND Supervisor_ID = $SuperID";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_array($query);
$Available = $row["$StartTime"];
echo "Is the Lecture Available? : $Available ";
$Time = "`$StartTime`";
if($Available == 1){
$sql = "INSERT INTO student_slot (Student_ID, Slot_ID) VALUES ($key, $value)";
$result = mysqli_query($con, $sql);
$sql = "UPDATE `supervisor_availability` SET $Time = '0' WHERE `supervisor_availability`.`Supervisor_ID` = $SuperID AND `supervisor_availability`.`Date_ID` = $DateID" ;
$result = mysqli_query($con, $sql);
} else if ($Available == 0) {
// Not sure what to do here.
// Can i make the Slot it's currently checking go to the end of the
// array for a different student and then check the next slot and come
// back to it.
}
}
I'm using echo for debugging.
The algorithm works fine if the Supervisor is available, it assigns it correctly and then updates the Supervisors availability for that time slot
Just need help with how to handle it if they're not available.
Any help or advice would be appreciated.
Supervisor_Availability Slot Table Student Table Date Table DB_Structure

restrict database row insert by a number?

Based on my codes, i need to restrict the insertion of the data by 3, i mean is like after the insertion of 3 data row, it will be restricted from inserting in data. Is that possible? For more information, is like the borrow inserting 3 times, then it cannot be inserted anymore. Is there anyway to do so? I am still learning php by the way, thank you.
if(isset($_POST['selector']))
$id=$_POST['selector'];
else
$id = '';
$member_id = $_POST['member_id'];
$due_date = $_POST['due_date'];
$isbn = $_POST['due_date'];
if ($id == '' ){
//header("location: borrow.php");
if(isset($_POST['isbn'])){
$isbn = $_POST['isbn'];
$query = mysql_query("select book_id from book WHERE isbn = '$isbn'")or die(mysql_error());
$count = mysql_num_rows($query);
if($count > 0){
$row = mysql_fetch_array($query);
$bookid = $row['book_id'];
$date = date('Y-m-d');
}
mysql_query("insert into borrow (member_id,book_id,date_borrow,due_date) values ('$member_id','$bookid','$date','$due_date')")or die(mysql_error());
}
else{
header("location: borrow.php");
}
}else{
mysql_query("insert into borrow (member_id,date_borrow,due_date) values ('$member_id',NOW(),'$due_date')")or die(mysql_error());
$query = mysql_query("select * from borrow order by borrow_id DESC")or die(mysql_error());
$row = mysql_fetch_array($query);
$borrow_id = $row['borrow_id'];
}else{
mysql_query("insert into borrow (member_id,date_borrow,due_date) values ('$member_id',NOW(),'$due_date')")or die(mysql_error());
$query = mysql_query("select * from borrow order by borrow_id DESC")or die(mysql_error());
$row = mysql_fetch_array($query);
$borrow_id = $row['borrow_id'];
$N = count($id);
for($i=0; $i < $N; $i++)
{
mysql_query("insert borrowdetails (book_id,borrow_id,borrow_status)
values('$id[$i]','$borrow_id','pending')")or die(mysql_error());
}
header("location: borrow.php");
}
You just have to count number of user row before to make a new insert :
$query = mysql_query("SELECT COUNT(*) AS count FROM borrow WHERE member_id = '".$member_id."'");
$row = mysql_fetch_assoc($query);
if ( $row['count'] >= 3 )
echo('Max insert');
Also, check this : Why shouldn't I use mysql_* functions in PHP?
I'm not sure I understand you correctly.
You can restrict the number of rows returned by SELECT query using the LIMIT clause.
Make sure you either put an ORDER BY clause in there or determine that you don't care 'which' 3 rows will get inserted.
See here:
http://dev.mysql.com/doc/refman/5.0/en/select.html

Categories