Calculate leaves from table for more than 1 leave entry - php

I have a database table in which leave will be updated.
It has the following columns:
id | empno | startdate | enddate | status | duration
Now I have to calculate the leave in a given month and year where the month and year will come from user input. I have a code which will retrieve the no. of leaves in the given month if the leave entry is 1.
The problem is that if the user has taken leave more than 1 time, the function is calculating only the last row from database. Any help would be appreciated.
<?PHP
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lms";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$empid = (isset($_POST['empid']) ? $_POST['empid'] : '');
$month = (isset($_POST['month']) ? $_POST['month'] : '');
$month = "2015-sep";
$month1 = date('F', strtotime('$month'));
//echo $month1;
$year = date('Y',strtotime('$month'));
$monthStart = date("Y-m-1") . "<br/>";
$num = cal_days_in_month(CAL_GREGORIAN, date("m"), date("Y"));
$monthEnd = date("Y-m-".$num)."<br/>";
//echo "$num";
$months = date('M');
$years = date ('Y');
$leave = 0;
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT `startdate`, `enddate`,`duration` FROM `leaves` WHERE `employee` = '2' AND `status` = '3'
AND `startdate` > '01-09-2015' AND `enddate` < '30-09-2015' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$start = ($row['startdate']);
$end = ($row['enddate']);
$startcount = ['COUNT(`employee`)'];
//$durationlvs = ($row['duration']);
echo "sdate:$start,edate:$end</br>";
//echo "lvsdur:$durationlvs";
}
function getLeavesInPeriod($start, $end) {
$date = new DateTime($start);
$endDate = new DateTime($end);
$leaves = array();
while( $date <= $endDate ) {
$year = $date->format('Y');
$month = $date->format('M');
if(!array_key_exists($year, $leaves))
$leaves[$year] = array();
if(!array_key_exists($month, $leaves[$year]))
$leaves[$year][$month] = 0;
$leaves[$year][$month]++;
$date->modify("+1 day");
}
return $leaves;
}
$leaves = getLeavesInPeriod($start,$end);
$noofleaves=$leaves[$years][$months];
echo $noofleaves;
$conn->close();
}
?>

Just changed the SQL Query to
$sql = "SELECT SUM(DATEDIFF(LEAST(enddate, '2015-09-30'),
GREATEST(startdate, '2015-09-01'))+1) days
FROM leaves WHERE
startdate<='2015-09-30' AND enddate>='2015-09-01' AND employee='2'
AND status='1'";
ufff!!! got the result.

Related

Issues ordering a resut from query

I am trying to order a 2nd query inside of a query loop, but doesn't seem to work... What I exactly want to achieve is to order the rows by ID, but at the 2nd query it doesn't work.
Here is the code:
<table>
<?php
function convertToHoursMins($time, $format = '%02d:%02d') {
if ($time < 1) {
return;
}
$hours = floor($time / 60);
$minutes = ($time % 60);
return sprintf($format, $hours, $minutes);
}
$servername = "xxxx";
$username = "xxxxx";
$password = "xxxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(!$_GET["steam"])
{
$steam = $steamprofile['steamid'];
}
else
{
$steam = intval($_GET["steam"]);
}
$sql = "SELECT * FROM `TotalVIPs`";
$conn->set_charset("utf8");
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//echo " <tr><th>". $row["SteamID"]."</th><td></tr>";
$sql2 = "SELECT * FROM `PlayedTime` WHERE `steamid` LIKE '". $row["SteamID"] ."' ORDER BY id ASC";
$conn->set_charset("utf8");
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
$time = $row2["AllTotal"];
$convtime = convertToHoursMins($time, '%d ore %d min');
$steamprof = "<a href='profile.php?steam=" . $row2["communityid"]. "' class='btn btn-default btn-xs'>Profil</a>";
echo " <tr><th>". $row2["id"]."</th><td>". $row2["playername"]."</td><td>". $row2["steamid"]."</td><td>". $convtime ."</td><td>". $row2["last_accountuse"]."</td><td>" . $steamprof . "</tr>";
}
}
}
}
$conn->close();
?>
</table>
I want it to order by ID, but doesn't do it for some reason.
Here, a photo: http://prntscr.com/neuu74
Since you're using nested loops, the overall results will be ordered by the results from the first query, and it will only order by id within each of the outer query's rows.
Instead, you should use a single query that joins the two tables, then you can order by a column in the second table.
SELECT *
FROM TotalVIPs AS v
JOIN PlayedTime AS p
ON p.steamid = v.steamid
ORDER by p.id

imap_open parse and insert into database

I am trying to fetch my emails, parse them, and insert them into my database. I am pretty far along on parsing, but the inserting part is not going well.
$headerost = 'imap.gmail.com';
$user = 'email#gmail.com ';
$pass = 'password';
$port = 993;
$protocol = "/imap/ssl";
$connect = imap_open("{{$headerost}:{$port}{$protocol}}INBOX", $user, $pass);
if (!$connect) die("Failed: $connect");
$count = imap_num_msg($connect);
for ($i = 1; $i <= $count; $i++) {
$header = imap_header($connect, $i);
$to = $header->to[0];
$from = $header->from[0];
$date = $header->date;
$date1 = date_create($date);
$date2 = date_format($date1, 'l - F jS, Y - g:i A');
$mailbox = quoted_printable_decode($from->mailbox);
$headerost = $from->host;
$email = "$mailbox#$headerost";
$mailbox1 = $to->mailbox;
$headerost1 = $to->host;
$email1 = "$mailbox1#$headerost1";
$letter = imap_fetch_overview($connect, $i);
$subj = imap_utf8( $letter[0]->subject);
$message = quoted_printable_decode(imap_fetchbody($connect, $i,1));
$query2 = "
SELECT *
FROM email
WHERE `email` = '$email'
AND 'date' = '$date2';
";
$result2 = mysql_query($query2);
$num = mysql_num_rows($result2);
$coming = "Client";
if ($num == 0) {
mysql_query ("
INSERT INTO email (
coming,
email,
date,
actualdate,
subject,
message
)
VALUES (
'$coming',
'$email',
'$date2',
'$date2',
'$subj',
'$message'
)
");
}
}
The $message is sometimes displaying the whole message, but sometimes it also displays replies, and sometimes it just displays gibberish. actual date is a date format in the MYSQL, and its entering at 00-00-0000. Email is entering as 0. $date2, $subj, and $coming are entering properly.

Function not returning values

I just asked a question earlier, but now i have formatted it into a function that does not return any value.
This is my code:
echo GetHours($UID, $DAY, $MONTH, $YEAR);
function GetHours($UserId, $Day, $Month, $Year){
//filter queries:
//YEAR:
if($Year==FALSE){
$Y = "";
} else {
$Y = " AND Year = '$Year'";
}
//MONTH:
if($Month==FALSE){
$M = "";
} else {
$M = " AND Month = '$Month'";
}
//DAY:
if($Day==FALSE){
$D = "";
} else {
$D = " AND Day = '$Day'";
}
$Query = mysql_query("SELECT SUM(TotalHrs)
FROM WorkLog
WHERE UserId = '$UserId'$D$M$Y");
$Data = mysql_fetch_array($Query);
return $Data;
}
Now, i do know that mysql_ functions are depreciated, but its required for this application at the moment.
My current problem is that this function does not return anything after using GET parameters to test.
Any solutions to this?
EDIT
I have changed the last lines to: return json_encode($Data); and now the screen shows: {"0":"8","SUM(TotalHrs)":"8"}
Always check that mysql_query() has not returned an error! Specially if you are building your query from parts generated from inputs that may or may not be present.
This should at least identify any errors in the SQL.
function GetHours($UserId, $Day, $Month, $Year){
//filter queries:
//YEAR:
if($Year==FALSE){
$Y = "";
} else {
$Y = " AND Year = '$Year'";
}
//MONTH:
if($Month==FALSE){
$M = "";
} else {
$M = " AND Month = '$Month'";
}
//DAY:
if($Day==FALSE){
$D = "";
} else {
$D = " AND Day = '$Day'";
}
$Query = mysql_query("SELECT SUM(TotalHrs)
FROM WorkLog
WHERE UserId = '$UserId'$D$M$Y");
if ( ! $Query ) {
// just debug code, should be amended for a live site situation
echo mysql_error();
return 'Its broken';
}
$Data = mysql_fetch_array($Query);
return $Data;
}
I figured out that the data i get returned was an array by doing echo json_encode(GetHours($UID, $DAY, $MONTH, $YEAR));
My finished code that works:
<?php
include 'assets/db_connect.php';
//Function to get total from WorkLog:
$DAY = $_GET['day'];
$MONTH = $_GET['month'];
$YEAR = $_GET['year'];
$UID = $_GET['id'];
echo GetHours($UID, $DAY, $MONTH, $YEAR);
function GetHours($UserId, $Day, $Month, $Year){
//filter queries:
//YEAR:
if($Year==FALSE){
$Y = "";
}
else{
$Y = " AND Year = '$Year'";
}
//MONTH:
if($Month==FALSE){
$M = "";
}
else{
$M = " AND Month = '$Month'";
}
//DAY:
if($Day==FALSE){
$D = "";
}
else{
$D = " AND Day = '$Day'";
}
$Query = mysql_query("SELECT SUM(TotalHrs) FROM WorkLog WHERE UserId = '$UserId'$D$M$Y");
$Data = mysql_fetch_array($Query);
return $Data['SUM(TotalHrs)'];
}

html multiple select statements not working

I have a form for adding events to each of my database tables.
In order for the data and time to be right I am using dropdown menus. However I am using 5 2 for the time and 3 for the date. In dream weaver on the second select statement it is highlighting it in yellow like I have an error. http://pastebin.com/NJB84hed
I would like to make sure this is also saving the id so that, the id can be posted in that table
$results=mysqli_query($con, "select * from Users where `userName` ='$username'");
$id = 'id_cust';
(1) You are missing a closing bracket } for your if(isset($_POST['insert'])){
if(isset($_POST['insert'])){
$artist = $_POST['artist'];
$place = $_POST['place'];
$hour = $_POST['hour'];
$minute = $_POST['min'];
$year = $_POST['year'];
$month = $_POST['month'];
$day = $_POST['day'];
$price = $_POST['price'];
$open = $_POST['open'];
$time = $hour.':'.$minute;
$date = $year.'-'.$month.'-'.$day;
$result=mysqli_query($con,"insert into Concert values('$id','$artist','$date','$time','$place','$price','$open')");
if($result)
{
echo 'Values updated successfully';
}
?>
Should be
if(isset($_POST['insert'])){
$artist = $_POST['artist'];
$place = $_POST['place'];
$hour = $_POST['hour'];
$minute = $_POST['min'];
$year = $_POST['year'];
$month = $_POST['month'];
$day = $_POST['day'];
$price = $_POST['price'];
$open = $_POST['open'];
$time = $hour.':'.$minute;
$date = $year.'-'.$month.'-'.$day;
$result=mysqli_query($con,"insert into Concert values('$id','$artist','$date','$time','$place','$price','$open')");
if($result)
{
echo 'Values updated successfully';
}
} // MISSING THIS CLOSING BRACKET
?>
(2) On line 73 you misspelled your select closing tag
</selct>
should be
</select>
(3) Also, I assume
$results=mysqli_query($con, "select * from Users where `userName` ='$username'");
$id = 'id_cust';
should be something like
$results=mysqli_query($con, "select * from Users where `userName` ='$username'");
$row = mysqli_fetch_array($result);
$id = $row['id_cust'];

Calculating the number of days between dates

I am trying to find out how many days between two date the code bellow is an example of what i am saying but it does not work all what i get in the database is 0
<?php
$hotel_name = $_POST['hotelName'];
$room_type = $_POST['roomType'];
//date From value
$dayfrom = $_POST['dayfrom'];
$monthfrom = $_POST['monthfrom'];
$yearfrom = $_POST['yearfrom'];
//date To value
$dayto = $_POST['dayto'];
$monthto = $_POST['monthto'];
$yearto = $_POST['yearto'];
$arivDate = sprintf('%04d-%02d-%02d', $yearfrom, $monthfrom, $dayfrom);
$depDate = sprintf('%04d-%02d-%02d', $yearto, $monthto, $dayto);
$child = $_POST['child'];
$adult = $_POST['adult'];
$days = $arivDate - $depDate;
//$sortedfromdate = strtotime($arivDate);
//$sortedtodate = strtotime($depDate);
$query = "INSERT INTO tempbooking( book_date, Ariv_date, dep_date, hotel_name
)VALUES(
CURDATE(), '{$arivDate}', '{$depDate}', '{$hotel_name}')";
if(mysql_query($query,$connection)){
$booking_id = mysql_insert_id();
}else{
die("The Booking was not successful". mysql_error());
}
$queryres="INSERT INTO ro_reservation( booking_id, children, adult, room_type, number_days
)VALUES(
{$booking_id}, {$child}, {$adult}, '{$room_type}',{$days})";
if(mysql_query($queryres,$connection)){
header("Location:index.php");
//echo" Reservation Inserted";
}else{
echo "Nothing was inserted in to the ro_reservation";
}
?>
$arivDate = strtotime("2012-01-01");
$depDate = strtotime("2012-08-14");
$datediff = abs($arivDate - $depDate)
echo floor($datediff/(60*60*24));

Categories