How should I write this specific condition in php? - php

The Challenge is:
If the book is returned on or before the expected return date, no
fine will be charged (i.e.: fine=0).
If the book is returned after the expected return day but still
within the same calendar month and year as the expected return date,
fine=15 Hackos × (the number of days late).
If the book is returned after the expected return month but still
within the same calendar year as the expected return date, the
fine=500 Hackos × (the number of months late).
If the book is returned after the calendar year in which it was
expected, there is a fixed fine of 10000 Hackos.
And My code is:
<?php
$expectedDay = "6";
$expectedMonth = "6";
$expectedYear = "2015";
$returnDay = "9";
$returnMonth = "6";
$returnYear = "2015";
if ($expectedDay >= $returnDay && $expectedMonth >= $returnMonth && $expectedYear >= $returnYear) {
echo "Fine = 0";
}elseif ($expectedDay < $returnDay && $expectedMonth == $returnMonth && $expectedYear == $returnYear) {
$fine = 15 * ($returnDay-$expectedDay);
echo "Fine = ".$fine;
}elseif (($expectedDay <= $returnDay || $expectedDay >= $returnDay) && $expectedMonth < $returnMonth && $expectedYear == $returnYear) {
$fine = 500 * ($returnMonth-$expectedMonth);
echo "Fine = ".$fine;
}else{
echo "Fine = 1000";
}
?>
Its running well.But failed when the input is:
$expectedDay = "28";
$expectedMonth = "2";
$expectedYear = "2015";
$returnDay = "15";
$returnMonth = "4";
$returnYear = "2015";
How do I write for this condition?
Note: This is not a business logic. It is just Practice purposes. I am a beginner in PHP.

Something along these lines:
function calculateLateFees(DateTime $deadline, DateTime $returned) {
if ($returned <= $deadline) {
return 0;
}
if ($returned->format('Y') > $deadline->format('Y')) {
return 10000;
}
if ($returned->format('n') > $deadline->format('n')) {
return ($returned->format('n') - $deadline->format('n')) * 500;
}
return $deadline->diff($returned)->days * 15;
}
$deadline = new DateTime('2015-02-28');
$returned = new DateTime('2015-04-15');
echo calculateLateFees($deadline, $returned), ' Hackos';

You do not have to compare dates when the month condition is checked.
<?php
$expectedDay = "6";
$expectedMonth = "6";
$expectedYear = "2015";
$returnDay = "9";
$returnMonth = "6";
$returnYear = "2015";
$returnDate = new DateTime($returnDay.'-'.$returnMonth.'-'.$returnYear);
$expectedDate = new DateTime($expectedDay.'-'.$expectedMonth.'-'.$expectedYear);
if ($returnDate <= $expectedDate) {
echo "Fine = 0";
}elseif ($expectedDay < $returnDay && $expectedMonth == $returnMonth && $expectedYear == $returnYear) {
$fine = 15 * ($returnDay-$expectedDay);
echo "Fine = ".$fine;
}elseif ($expectedMonth < $returnMonth && $expectedYear == $returnYear) {
$fine = 500 * ($returnMonth-$expectedMonth);
echo "Fine = ".$fine;
}else{
echo "Fine = 1000";
}
?>
Try that.

First, I must say that this is a very unfair calculation of fines. What if the expected day is 31.12.2016 and the book was returned 01.01.2017? According to your method the a fine of 10000 will be imposed for the lapse of one day just because it was across the margin of two separate years.
I would recommend you to calculate the fine according to the number of days late.
$lateDays = date_diff($expectedDate, $returnDate, false);
if ($lateDays > 0) {
if ($lateDays < 30)
$fine = 15 * $lateDays
else
if ($lateDays > 365)
$fine = 10000
else
$fine = 500 * $lateDays / 30
}

if($returnYear > $expectedYear){
$fine = 1000;
}
else{
if($returnMonth > $expectedMonth ){
$fine = 500 * ($returnMonth-$expectedMonth);
}
else{
if($returnDay>$expectedDay){
$fine = $returnDay - $expectedDay;
}
else{
$fine = 0;
}
}
}
echo $fine;
Above logic is built taken into consideration that months in number crossed will take complete month cost example :
if expected return date is 28/04/2016 and actual return date is 02/05/2016 then since month is changed the below algorithm takes fine #complete month.
If you want exact days difference to be considered for months/year calculation then we can write a different logic all together

<?php
$expectedDay = "6";
$expectedMonth = "6";
$expectedYear = "2015";
$returnDay = "9";
$returnMonth = "6";
$returnYear = "2015";
$expectedate=$expectedYear.'-'.$expectedMonth.'-'.$expectedDay;
$returndate=$returnYear.'-'.$returnMonth.'-'.$returnDay;
$expected=date_create($expectedate);
$return=date_create($returndate);
$interval=date_diff($expected, $return);
$valor=$interval->format('%R%a');
if ($valor>0) {
if ($returnMonth==$expectedMonth && $returnYear==$expectedYear) echo "Fine=".(15*$valor);
if ($returnMonth!=$expectedMonth && $returnYear==$expectedYear) echo "Fine=".(500*($returnMonth-$expectedMonth));
if ($returnYear!=$expectedYear) echo "Fine=1000";
} else echo "Fine=0";
?>

Related

Finding certain percentages from function

I'm making a grade calculator where the user inputs their earned points, points possible, then its weight within the class. Afterwards it then calculates and prints the percentage earned for each portion along with its weight. Finally, it prints your total calculated score along with the letter grade. I'm able to print the very last line completely, along with each categories' weight, but I can't print out the percentage earned in each category
<?php
$par_Earned = $_POST['earnedParticipation'];
$par_Possible = $_POST['maxParticipation'];
$par_Weight = $_POST['weightParticipation'];
$q_Earned = $_POST['earnedQuiz'];
$q_Possible = $_POST['maxQuiz'];
$q_Weight = $_POST['weightQuiz'];
$l_Earned = $_POST['earnedLab'];
$l_Possible = $_POST['maxLab'];
$l_Weight = $_POST['weightLab'];
$p_Earned = $_POST['earnedPracticum'];
$p_Possible = $_POST['maxPracticum'];
$p_Weight = $_POST['weightPracticum'];
function percentage($a,$b){
$percent = ($a/$b)*100;
return $percent;
}
function weightValue($c,$d,$e){
$weight = (percentage($c,$d) * $e)/100 ;
return $weight;
}
$parWeight = weightValue($par_Earned,$par_Possible,$par_Weight);
$quizWeight = weightValue($q_Earned,$q_Possible,$q_Weight);
$labWeight = weightValue($l_Earned,$l_Possible,$l_Weight);
$pracWeight = weightValue($p_Earned,$p_Possible,$p_Weight);
$total = $parWeight+$quizWeight+$labWeight+$pracWeight;
function lettergrade($total) {
if ($total >= 95) {
$lettergrade = "A+";
}
else if ($total < 95 && $total >= 90 ) {
$lettergrade = "A";
}
else if ($total < 90 && $total >= 85) {
$lettergrade = "B+" ;
}
else if ($total < 85 && $total >= 80) {
$lettergrade = "B" ;
}
else if ($total < 80 && $total >= 75) {
$lettergrade = "C+" ;
}
else if ($total < 75 && $total >= 70) {
$lettergrade = "C" ;
}
else if ($total < 70 && $total >= 60) {
$lettergrade ="D" ;
}
else if ($total < 60 && $total >= 0) {
$lettergrade = "F" ;
}
else {
$lettergrade = "Grade is not valid";
}
return $lettergrade;
}
echo "<p>You earned a X with a weighted value of " .$par_Weight. "% </p>";
echo "<p>You earned a X with a weighted value of " .$q_Weight. "% </p>";
echo "<p>You earned a X with a weighted value of " .$l_Weight. "% </p>";
echo "<p>You earned a X with a weighted value of " .$p_Weight. "% </p>";
echo "<p><b>Your final grade is " .$total. "%, which is a ".lettergrade($total)."</b></p>";
?>

Display students grades in alphabetical order

I've been able to display the number of times each grade appears on a student's report sheet. However, they are not sorted alphabetically.
grade image
The image above shows that the student got 2Bs, 4B+, 3As, and 1E. My code displays it like this.
But I want the grades to be displayed in alphabetical order like this 3As, 2Bs, 4B+, and 1E.
How do I do that?
Here is my code
<?php $i = 1;
$total = 0;
$count = count($subjectScores);
$grades_count = [];
foreach ($subjectScores as $value) { ?>
<?php
if ($value->tot_score >= 90 && $value->tot_score <= 100) {
$grade = 'A+';
$remark = 'DISTINCTION';
} elseif ($value->tot_score >= 80 && $value->tot_score <= 89.99) {
$grade = 'A';
$remark = 'EXCELLENT';
} elseif ($value->tot_score >= 70 && $value->tot_score <= 79.99) {
$grade = 'B+';
$remark = 'VERY GOOD';
} elseif ($value->tot_score >= 60 && $value->tot_score <= 69.99) {
$grade = 'B';
$remark = 'GOOD';
} elseif ($value->tot_score >= 50 && $value->tot_score <= 59.99) {
$grade = 'C';
$remark = 'ABOVE AVERAGE';
} elseif ($value->tot_score >= 45 && $value->tot_score <= 49.99) {
$grade = 'D';
$remark = 'AVERAGE';
} elseif ($value->tot_score >= 40 && $value->tot_score <= 44.99) {
$grade = 'E';
$remark = 'FAIR';
} elseif ($value->tot_score >= 0 && $value->tot_score <= 39.99) {
$grade = 'F';
$remark = 'NEEDS SERIOUS IMPROVEMENT';
}
// declare count for grade initially with 0
if(isset($grades_count[$grade]) === false) {
$grades_count[$grade] = 0;
}
{
// increment count for given grade
$grades_count[$grade]++;
}
?>
<?php foreach ($grades_count as $grade=>$count) {
echo "$count$grade ";
} ?>

PHP function inside query wont return value

So, I have a PHP Script that would insert an attendance of the student. First it should check if the attendance with the same student ID and date already exist. If not, it inserts the attendance. I want to insert in the attendance status whether the student is present or late based on my php function compareTime's return value. But the problem is, the function wont return anything. That's why in the attendance data the status column is blank.
function checkAttendance($conn, $stud_id) {
$check = mysqli_query($conn, "SELECT * FROM tbl_attendance WHERE student_id = '$stud_id' AND date = CURDATE()") or die (mysqli_error());
if(mysqli_num_rows($check) > 0) {
return true;
}
else {
return false;
}
}
function compareTime($time,$grade) {
$ctime = strtotime($time);
if($grade == "H1" || $grade == "H2" || $grade == "H3" || $grade == "H4" || $grade == "S1" || $grade == "S2") {
if ($ctime > strtotime('05:00:00') && $ctime < strtotime('07:30:00')) return "P";
else if ($ctime > strtotime('07:30:00') && $ctime < strtotime('8:30:00')) return "L";
}
else {
if($ctime > strtotime('05:00:00') && $ctime < strtotime('07:15:00'))
return "P";
else if ($ctime > strtotime('07:15:00') && $ctime < strtotime('8:30:00'))
return "L";
}
}
function recordAttendance($conn, $sid, $glid, $scid) {
$sql = mysqli_query($conn, "INSERT INTO tbl_attendance(student_id, gradeLevel_id, section_id, date, arrival_time, status) VALUES ('".$sid."', '".$glid."', '".$scid."', CURDATE(), CURTIME(), '".compareTime(date('H:i:s'),$glid)."')") or die(mysqli_error());
}
$res = mysqli_query($connect, "SELECT * FROM tbl_student WHERE card_id = '$cardID'")or die(mysqli_error());
while($row = mysqli_fetch_array($res,MYSQLI_ASSOC)) {
if (checkAttendance($connect, $row['student_id']))
echo "Already Exist!";
else
recordAttendance($connect, $row['student_id'], $row['gradeLevel_id'], $row['section_id']);
}
It could have several reasons actually, but you'll need to debug to see which is the case.
First start debugging by outputting the values of compareTime to see if they actually work at all. If it doesn't, fix that first.
If that works you could try adding a 'hardcoded' value to your query to see if that gets inserted into your (test) data/table. If that doesn't produce a good result either it might be a case of wrong type in the database. Maybe it's expecting an integer or something else?
You could also extract the function call from the query and put it in a variable, it will provide a bit cleaner and more readable code, as well as it being easier to debug.
p.s.
Did you realise that, in the unlikely event of a time being exactly 7:30:00 or 7:15:00, a person falls between the cracks because you only check for greater or smaller than. Some should also be >= or <=
Might be better to rewrite it to something like this:
function compareTime($grade,$time = ''){
$time = (empty($time))?strtotime(date('H:i:s')):strtotime($time);
$time_5 = strtotime('05:00:00');
$time_715 = strtotime('07:15:00');
$time_730 = strtotime('07:30:00');
$time_830 = strtotime('08:30:00');
if ($grade == "H1" || $grade == "H2" || $grade == "H3" || $grade == "H4" || $grade == "S1" || $grade == "S2") {
if (
$time > $time_730
&& $time < $time_830
){
return "L";
} elseif (
$time > $time_5
&& $time <= $time_730
){
return "P";
}
} else {
if (
$time > $time_715
&& $time < $time_830
){
return "L";
} elseif (
$time > $time_5
&& $time <= $time_715
){
return "P";
}
}
}

New Error.. Cant Figure This One Out

My timestamp code worked well before i put it in a function.. Get this parse error on line 55, ive marked the line number with "// LINE 55", cant figure it out :(
Here's my error:
Parse error: syntax error, unexpected '.' in C:\wamp\www\flueforumdk\config.php on line 55
Here's the calling of the function:
$GET_UNIX_STAMP_FROM_DB = $art[tidspunkt];
$UNIX_TIME_SECONDS = $GET_UNIX_STAMP_FROM_DB;
echo timestamp_converter($UNIX_TIME_SECONDS);
Here's my function code:
## TIMESTAMP CONVERTER FUNCTION
function timestamp_converter($UNIX_TIME_SECONDS){
// UDREGNING FRA UNIX TIME
$tid = time() - $UNIX_TIME_SECONDS;
$timer = floor($tid/3600);
$minutter = floor($tid/60);
$dage = floor($timer / 24);
$uge = floor($dage / 7);
$month = floor($dage / 30.5);
$aar = floor($dage / 365);
if($tid < 60){
echo"<b>$tid</b> sekunder";
} elseif ($tid > 60){
echo"";
}
if($minutter == 0){
echo"";
} elseif ($minutter < 60){
if($minutter == 1){
echo"<b>$minutter</b> minut";
}else{
echo"<b>$minutter</b> minutter";
}
}
if($timer == 0){
echo"";
} elseif ($timer < 24){
if($timer == 1){
echo"<b>$timer</b> time";
}else{
echo"<b>$timer</b> timer";
}
}
//LINE 55 if($dage == 0){
echo"";
} elseif ($dage < 7){
if($dage == 1){
echo"<b>$dage</b> dag";
}else{
echo"<b>$dage</b> dage";
}
}
if($uge == 0){
echo"";
} elseif ($uge < 4){
if($uge == 1){
echo"<b>$uge</b> uge";
}else{
echo"<b>$uge</b> uger";
}
}
if($month == 0){
echo"";
} elseif ($month < 12){
if($month == 1){
echo"<b>$month</b> måned";
}else{
echo"<b>$month</b> måneder";
}
}
if($aar == 0){
echo"";
} elseif ($aar > 0){
if($aar == 1){
echo"<b>$aar</b> år";
}else{
echo"<b>$aar</b> år";
}
}
}

PHP echo only 1 higher or 1 lower then current hour

So I'm having this issue where I want to echo only the things that are 1 higher or 1 lower then the current hour. Example if current hour = 14 only echo 13, 14 and 15
Anyone have a clue on how I can do this?
<?php
mysql_connect("*******", "******", "**");
if(!mysql_select_db("deb67423_dj")) {
die("<b>Mislukt!</b><br>Het verbinden met de database is mislukt.");
}
$textweek = date("D");
if($textweek == "Mon") {
$dag = 0;
} else
if($textweek == "Tue") {
$dag = 1;
} else
if($textweek == "Wed") {
$dag = 2;
} else
if($textweek == "Thu") {
$dag = 3;
} else
if($textweek == "Fri") {
$dag = 4;
} else
if($textweek == "Sat") {
$dag = 5;
} else
if($textweek == "Sun") {
$dag = 6;
}
$textuur = date("G");
$SQL = "SELECT * FROM rooster WHERE dag = '$dag'";
$result = mysql_query($SQL);
echo "<table>";
while ($row = mysql_fetch_assoc($result)) {
echo "<td> Hiervoor: DJ ".$row['gebruikersnaam']. "</td>";
}
echo "</table>";
$currHour = date('G');
echo $currHour - 1, ', ', $currHour, ', ', $currHour + 1;
Take note that $currHour can be 0 and you will have to take care of this "special" case... But I think this snippet will get you started. See the PHP date() documentation for more help.

Categories