Calculating the number of days between dates - php

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));

Related

How to retrieve data from a MYSQL Database and do validation in Android on Button click

I have an Android app which is used to insert user records for each User.Each user can input data into the database only 2 times a day. If the user tries to input data the third time(click the Submit button),a new activity(in Android) will be shown with a message and the date field(TextView) should be incremented by 1 Day.I am able to add the date field by 1 day on every click. So what I have tried is to get the count of data in the MYSQL database of each user for the particular day and if the count is greater than 3, then the PHP Script will return an echo statement according to which the Async Task in Anroid will function and show the new Activity.
My PHP Script is:
<?php
require "conn.php";
require "SalesLogin.php";
$enquiry = $_POST["enquiry"];
$retail = $_POST["retail"];
$collection = $_POST["collection"];
$booking = $_POST["booking"];
$evaluation = $_POST["evaluation"];
$test_drive = $_POST["test_drive"];
$home_visit = $_POST["home_visit"];
$user_name = $_POST["user_name"];
$update_date = $_POST["date"];
$absent = $_POST["absent"];
$timezone = new DateTimeZone("Asia/Kolkata" );
$date = new DateTime();
$date->setTimezone($timezone );
$time = $date->format( 'H:i:s A' );
$sql = "UPDATE employee_details SET
enquiry_sum = (SELECT SUM(enquiry) +'$enquiry' FROM (SELECT * FROM employee_details WHERE date = CURDATE() AND name = '$user_name') AS x)
WHERE date = CURDATE() AND name = '$user_name'";
$res = $conn->query($sql);
$check = "UPDATE employee_details SET enquiry_target_status = ( SELECT IF (MAX(enquiry_sum) = 52, 'ACHIEVED', 'NOT ACHIEVED') FROM (SELECT * from employee_details WHERE date = CURDATE() AND name = '$user_name') AS Y ) WHERE date = CURDATE() AND name = '$user_name'";
$insert_status = $conn->query($check);
$miss_count = "UPDATE employee_details SET enquiry_target_missed_by = (SELECT (50 - MAX(enquiry_sum)) FROM (SELECT * from employee_details WHERE date = CURDATE() AND name = '$user_name') AS Z ) WHERE date = CURDATE() AND name = '$user_name'";
$insert_status = $conn->query($miss_count);
$mysql_qry1 = "INSERT INTO employee_details(enquiry,retail,
collection,booking, evaluation, test_drive, home_visit, name, date,time,absent) values ('$enquiry','$retail','$collection','$booking','$evaluation','$test_drive',
'$home_visit','$user_name','$update_date','$time','$absent');";
if($conn->query($mysql_qry1) === TRUE)
echo "Your details has been successfully inserted.";
else
echo "Error: " .$mysql_qry1. "<br>" . $conn->error;
if($update_date != $date){
$mysql_qry2 = "UPDATE employee_data SET last_updated_date = (DATE_ADD('$update_date', INTERVAL 1 DAY)) WHERE name = '$user_name';";
$conn->query($mysql_qry2);
echo "Date changed," .$mysql_qry2;
}
$mysql_qry3 = "SELECT COUNT(*) from employee_details WHERE date = '$update_date' and name LIKE '$user_name';";
$conn->query($mysql_qry3);
if($mysl_qry3 <= 2)
{
echo "You can login.";
}
else
{
echo "You cannot login anymore for today.";
}
$conn->close();
?>
My AsyncTask code is:
#Override
protected void onPostExecute(String result) {
try {
if (result.contains("Welcome") && result.contains("Date")) {
String[] str = result.split("_");
String name = str[1];
String[] date = result.split(":");
String upd_date = date[1];
Intent intent = new Intent(context,InsertDataActivity.class);
intent.putExtra("username",name);
intent.putExtra("date",upd_date);
context.startActivity(intent);
}
else if (result.contains("Login failed.") && !(result.contains("Undefined")))
Toast.makeText(context,"Invalid Crendentials.",Toast.LENGTH_LONG).show();
else if (result.contains("You cannot login anymore for today.")) {
Log.i("Check",result);
Intent intent = new Intent(context,ThankYouActivity.class);
context.startActivity(intent);
}
} catch (NullPointerException e) {
Toast.makeText(context,"No Internet Connectivity found.Please connect to the internet first and then retry.",Toast.LENGTH_LONG).show();
}
}
But my code is not working properly. Can anyone please help me with this?
I solved the problem using the below PHP Script. I did not use alias for the SQL output which is done using "AS". The below script is working fine and gives the desired result.
<?php
require "conn.php";
require "SalesLogin.php";
$enquiry = $_POST["enquiry"];
$retail = $_POST["retail"];
$collection = $_POST["collection"];
$booking = $_POST["booking"];
$evaluation = $_POST["evaluation"];
$test_drive = $_POST["test_drive"];
$home_visit = $_POST["home_visit"];
$user_name = $_POST["user_name"];
$update_date = $_POST["date"];
$absent = $_POST["absent"];
$timezone = new DateTimeZone("Asia/Kolkata" );
$date = new DateTime();
$date->setTimezone($timezone );
$time = $date->format( 'H:i:s A' );
$sql = "UPDATE employee_details SET
enquiry_sum = (SELECT SUM(enquiry) +'$enquiry' FROM (SELECT * FROM employee_details WHERE date = CURDATE() AND name = '$user_name') AS x)
WHERE date = CURDATE() AND name = '$user_name'";
$res = $conn->query($sql);
$check = "UPDATE employee_details SET enquiry_target_status = ( SELECT IF (MAX(enquiry_sum) = 52, 'ACHIEVED', 'NOT ACHIEVED') FROM (SELECT * from employee_details WHERE date = CURDATE() AND name = '$user_name') AS Y ) WHERE date = CURDATE() AND name = '$user_name'";
$insert_status = $conn->query($check);
$miss_count = "UPDATE employee_details SET enquiry_target_missed_by = (SELECT (50 - MAX(enquiry_sum)) FROM (SELECT * from employee_details WHERE date = CURDATE() AND name = '$user_name') AS Z ) WHERE date = CURDATE() AND name = '$user_name'";
$insert_status = $conn->query($miss_count);
$mysql_qry1 = "INSERT INTO employee_details(enquiry,retail,
collection,booking, evaluation, test_drive, home_visit, name, date,time,absent) values ('$enquiry','$retail','$collection','$booking','$evaluation','$test_drive',
'$home_visit','$user_name','$update_date','$time','$absent');";
if($conn->query($mysql_qry1) === TRUE)
echo "Your details has been successfully inserted.";
else
echo "Error: " .$mysql_qry1. "<br>" . $conn->error;
if($update_date != $date){
$mysql_qry2 = "UPDATE employee_data SET last_updated_date = (DATE_ADD('$update_date', INTERVAL 1 DAY)) WHERE name = '$user_name';";
$conn->query($mysql_qry2);
echo "Date changed," .$mysql_qry2;
}
$mysql_qry3 = "SELECT COUNT(*) AS count from employee_details WHERE date = '$update_date' and name LIKE '$user_name';";
$result1 = mysqli_query($conn,$mysql_qry3);
$row = mysqli_fetch_assoc($result1);
$count = $row['count'];
echo "Count: " .$count;
if($count <= 2)
{
echo "You can login.";
}
else
{
echo "You cannot login anymore for today.";
}
$conn->close();
?>

inserting record if count of column is less than two else not inserting into mysql

just want to add record if count of column is less than 2 for today's date and if count is more than two it should not get insert into the db.It's keep getting added after two records.
$user_ip = getenv('REMOTE_ADDR');
$geo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$user_ip"));
$city = $geo["geoplugin_city"];
$region = $geo["geoplugin_regionName"];
$img = $_POST['img'];
$amount = 5;
$sql = "SELECT COUNT(*) as totalupload FROM `daily_uploads` WHERE DATE_FORMAT(`date`, '%Y-%m-%d') = CURDATE()";
$row = mysqli_fetch_assoc($sql);
$sum = $row['totalupload'];
if ($sum < 2 ) {
$sql = "INSERT INTO `daily_uploads` (img, geoplugin_city, geoplugin_regionName, amount)
VALUES ('$img', '$city', '$region','$amount')";
if ($conn->query($sql)) {
echo ('success');
} else {
echo ('error');
}
} else {
echo"already exist";
make the connection after count query like this,
$result = mysqli_query($con,$sql);
Try this one hope it will help you.
$user_ip = getenv('REMOTE_ADDR');
$geo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$user_ip"));
$city = $geo["geoplugin_city"];
$region = $geo["geoplugin_regionName"];
$img = $_POST['img'];
$amount = 5;
$sql = "SELECT COUNT(*) as totalupload FROM `daily_uploads` WHERE DATE_FORMAT(`date`, '%Y-%m-%d') = CURDATE()";
$qry= mysql_query($sql);
$row = mysql_fetch_assoc($qry);
$count = $row['totalupload'];
if ($count < 2 ) {
$sql = "INSERT INTO `daily_uploads` (img, geoplugin_city, geoplugin_regionName, amount)
VALUES ('$img', '$city', '$region','$amount')";
if ($conn->query($sql)) {
echo ('success');
} else {
echo ('error');
}
} else {
echo"already exist";

Calculate leaves from table for more than 1 leave entry

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.

how can I put validation if the record is inserted today?

$days = date('Y-m-d ', mktime($count['time_in']));
$date_today = date('Y-m-d');
if ($days != $date_today) {
$sql = "INSERT INTO login_details (time_in, user_id) VALUES (CURRENT_TIMESTAMP, '".$_SESSION['user_id']."') ";
$result = mysql_query($sql);
} else{
echo "<h3 align=center>Already exist!</h3>";
header ('refresh: 3; URL = index.php?page=timerecord');
}
time_in column should be in database should be datetime data type.
$date_today = date('Y-m-d');
$selectSql=mysql_query("SELECT count(*) as logincount from login_details where time_in=date(now())");
$countLogin=mysql_result($selectSql,0,'logincount');
if($countLogin>0){
} else {
$sql = mysql_query("INSERT INTO login_details (time_in, user_id) VALUES ('".$date_today."', '".$_SESSION['user_id']."')");
}

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'];

Categories