PHP echo only 1 higher or 1 lower then current hour - php

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.

Related

Creating two triangle using php

Someone please help me to create a two triangle patter using PHP. I'm already code but the output didn't as expected below.
expected output
My code:
function generatePattern($num) {
for ($id1 = 0; $id1 <= $num; $id1 = $id1 + 1) {
for ($id2 = $num; $id2 >= $id1; $id2 = $id2 - 1) {
print(' ');
}
for ($id3 = 1; $id3 <= $id1; $id3 = $id3 + 1) {
if ($id3 % 4 == 3) {
echo "o";
} else if ($id3 % 2 == 1) {
echo "x";
} else {
echo " ";
}
}
echo "\n";
}
for ($id1 = 0; $id1 <= $num-1; $id1 = $id1 + 1) {
echo str_repeat(' ', $num - 1);
for($id3 = $num-1; $id3 >= $id1; $id3 = $id3 - 1){
if ($id3 % 4 == 3) {
echo "o";
} else if ($id3 % 2 == 1) {
if ($id1 % 4 == 3) {
echo "o";
} else if ($id1 % 2 == 0) {
echo " ";
} else if ($id1 % 2 == 1) {
echo "x";
} else {
echo "x";
}
} else if ($id3 == $id1){
echo "x";
} else {
echo " ";
}
}
echo "\n";
}
}
generatePattern(4);
And my current output like this (the bottom triangle still messed up)
output
Do the required changes for space between o and x
function generatePattern($num) {
if($num % 2 == 0)
{
$num1 = $num + 1;
}else{
$num1 = $num;
$num = $num - 1;
}
for ($id1 = 1; $id1 <= $num; $id1++) {
for ($id2 = $num; $id2 >= $id1; $id2--) {
print(' ');
}
for ($id3 = 1; $id3 <= $id1; $id3++) {
if ($id3 % 4 == 3) {
echo "o";
} else if ($id3 % 2 == 1) {
echo "x";
} else {
echo " ";
}
}
echo "\n";
}
$str = str_repeat('x o ', ceil(($num1*2)/4));
echo substr($str, 0, $num1*2);
echo "\n";
$j = $num;
for($id1 = $num; $id1 >=1; $id1 = $id1 - 2)
{
for($id2 = 2; $id2 >= 1; $id2--)
{
if($j % 2 == 0)
{
$pattern = [' ', 'x', ' ', 'o',];
}else{
$pattern = [' ', 'o', ' ', 'x',];
}
echo str_repeat(' ', ($id2%2 == 0) ? $num: $num - 1);
$design = implode('', $pattern);
do{
$design .= implode('', $pattern);
}while(strlen($design) < $id1);
echo substr($design, 0, $id1);
echo "\n";
}
$j--;
}
}
generatePattern(14);

How should I write this specific condition in 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";
?>

schedule: click book time slot to display image of specific user that is booking? HOW PLEASE?

Ok, i have my php code wrote out for the schedule to book time slots. The sql is pulling the user name (text) and displaying it, BUT I AM NOW TRYING TO DISPLAY THE USERS PIC IMAGE INSTEAD OF JUST NAME(text). I cant for the life of me find anything that is clearly telling me how to display an image on click instead of the text from sql. PLEASE HELP, THANKS :)
ENTIRE CODE:
<?php require('head.php');?>
<?php
// Basic info
$slotb = $_GET['slot'];
$day = $_GET['day'];
// User info
$username = $_SESSION['rp_username'];
$avatar = $_SESSION['rp_avatar'];
$rank = $_SESSION['rp_rank'];
// Get user's ID
$sql = mysql_query("SELECT id, username FROM rp_users WHERE username = '$username'");
while($row = mysql_fetch_array($sql))
{
$userid = $row['id'];
}
// Determine day of week
if($_GET['week'] == "")
{
$_GET['week'] = date("l");
}
// Determine day of week
if($_GET['day'] == ""){
$day = $_GET['week'];
$_GET['week'] = date("l");
}
// Get slot info
$slot = mysql_fetch_array(mysql_query("SELECT * FROM rp_timetable WHERE day = '$day'"));
// Timetable heading
echo "<div id='timetable'><center><b><u>Timetable</u></b><p>
<h1>-You are currently viewing $day's timetable-</h1><p>
<a href='?week=Monday'>Monday</a> | <a href='?week=Tuesday'>Tuesday</a> | <a href='? week=Wednesday'>Wednesday</a> | <a href='?week=Thursday'>Thursday</a> | <a href='? week=Friday'>Friday</a> | <a href='?week=Saturday'>Saturday</a> | <a href='? week=Sunday'>Sunday</a><br><hr><br>";
// Process booking
if($_GET["action"] == "book")
{
if($slot[$slotb] == "")
{
$command = mysql_query("UPDATE rp_timetable SET `$slotb` = '$userid' WHERE day = '$day'") or die(mysql_error());
if($command)
{
echo "<center><h1>Successfully booked slot!</h1></center><br/>";
$slot = mysql_fetch_array(mysql_query("SELECT * FROM rp_timetable WHERE day = '$day'"));
}else{
echo "<center><h1>ERROR - An unknown error occurred, please try again.</h1></center> <br/>";
}
}else{
echo "<center><h1>The selected slot is already booked!</h1></center><br/>";
}
}elseif($_GET["action"] == "unbook")
{
if($slot[$slotb] == $userid || $rank == "Administrator")
{
$command = mysql_query("UPDATE rp_timetable SET `$slotb` = '' WHERE day = '$day'") or die(mysql_error());
if($command)
{
echo "<center><h1>Successfully unbooked slot!</h1></center><br/>";
$slot = mysql_fetch_array(mysql_query("SELECT * FROM rp_timetable WHERE day = '$day'"));
}else{
echo "<center><h1>ERROR - An unknown error occurred, please try again.</h1></center> <br/>";
}
}else{
echo "<center><h1>You cannot unbook this slot!</h1></center><br/>";
}
}
elseif($_GET["action"] == "empty"){
if($rank == "Administrator")
{
$command = mysql_query("UPDATE rp_timetable SET `1`='', `2`='', `3`='', `4`='', `5`='', `6`='', `7`='', `8`='', `9`='', `10`='', `11`='', `12`='', `13`='', `14`='', `15`='', `16`='', `17`='', `18`='', `19`='', `20`='', `21`='', `22`='', `23`='', `24`='' WHERE day='$day'") or die(mysql_error());
if($command)
{
echo "<center><h1>Successfully cleared all slots for day!</h1></center><br/>";
$slot = mysql_fetch_array(mysql_query("SELECT * FROM rp_timetable WHERE day = '$day'"));
}else{
echo "<center><h1>ERROR - An unknown error occurred, please try again.</h1></center><br/>";
}
}
else{
echo "<center><h1>Only administrators may unbook all slots for the day!</h1></center> <br/>";
}
}
// Start of timetable
echo "<table border='0' valign='middle' align='center'><tr>
<td width='150px' align='center'><b><u>Time</u></b></td>
<td width='150px' align='center'><b><u>DJ Booked</u></b><td></tr>
<tr><td></td><td></td></tr>";
// Display each timeslot/table
function outit($time, $num)
{
global $day, $slot, $userid, $rank;
$info = mysql_fetch_array(mysql_query("SELECT * FROM rp_users WHERE id = '".$slot[$num]."'"));
if($slot[$num] == "")
{
$book[$num] = "<a href='?action=book&day=$day&slot=$num'>BOOK SLOT</a>";
}
elseif($userid == $slot[$num] || $rank == "Administrator")
{
$book[$num] = "<a href='?action=unbook&day=$day&slot=$num'><b>DJ ".$info['avatar']." (Unbook)</a></b>";
}else{
$book[$num] = "<b><font color='black'>DJ ".$info['avatar']."</font></b>";
}
if($num%2)
{
echo "<tr class='colour'><td width='150px' align='center'>$time</td><td width='150px' align='center'>".$book[$num]."<td></tr>";
}else{
echo "<tr><td width='150px' align='center'>$time</td><td width='150px' align='center'>".$book[$num]."<td></tr>";
}
}
// Print it out
outit('12:00 - 01:00 AM', 1);
$i = 2;
while($i <= 12)
{
$start_time = $i - 1;
$end_time = $i;
if(strlen($start_time) == 1){$start_time = "0".$start_time;}
if(strlen($end_time) == 1){$end_time = "0".$end_time;}
$full_time = "$start_time:00 - $end_time:00 AM";
outit($full_time, $i);
$i++;
}
outit('12:00 - 01:00 PM', 13);
$i = 14;
while($i <= 24)
{
$start_time = $i - 13;
$end_time = $i - 12;
if(strlen($start_time) == 1){$start_time = "0".$start_time;}
if(strlen($end_time) == 1){$end_time = "0".$end_time;}
$full_time = "$start_time:00 - $end_time:00 PM";
outit($full_time, $i);
$i++;
}
// Bottom of timetable
echo "<tr><td align='center'>---------------</td><td align='center'>--------------- </td></tr>";
echo "<tr><td width='150px' align='center'><b>$day</b></td>
<td width='150px' align='center'>";
if ($_SESSION["rp_rank"] == "Administrator")
{
echo("<a href='?action=empty&day=$day'>CLEAR DAY</a>");
}
echo "</td></tr></table>
</center><p></div>";
?>
<?php require('bottom.php');?>
To use the $avatar variable that seems to be stored in your session:
echo '<img src="'.$avatar.'"></img';
You also seem to be selecting that field in the query $info, meaning you should be able to use the following as well:
echo '<img src="'.$info['avatar'].'"></img';
To isolate the problem, please let me know what output you get for just the following:
<?php require('head.php');?>
<?php
// Basic info
$slotb = $_GET['slot'];
$day = $_GET['day'];
// User info
$username = $_SESSION['rp_username'];
$avatar = $_SESSION['rp_avatar'];
$rank = $_SESSION['rp_rank'];
echo $avatar;
<?php require('bottom.php');?>
My guess is that $avatar holds apostrophes or other characters that need to be escaped.
Also could you provide a couple examples of the field values for the avatar column on the rp_users table? If they contain apostrophes, then that is your answer.

For loop variable, confused about single and double quotes

I'd like to make the following code a for loop to make everything read better, but I can't seem to get the quotes right and end up with a blank page
if ($_POST['week'])
{
$week = $_POST['week'];
}
//or check for a value submitted by the week menu
elseif ($_POST["user_week1"] == "week1") {
$week = "1";
}
elseif ($_POST["user_week2"] == "week2") {
$week = "2";
}
else if ($_POST["user_week3"] == "week3") {
$week = "3";
}
else if ($_POST["user_week4"] == "week4") {
$week = "4";
}
else if ($_POST["user_week5"] == "week5") {
$week = "5";
}
else if ($_POST["user_week6"] == "week6") {
$week = "6";
}
else {
$week = "1";
}
I tried to do:
if ($_POST['week'])
{
$week = $_POST['week'];
}
for ($i = 1; $i<7; $i++)
{
else if ($_POST["user_week'.$i.'"] == "week'.$i.'") {
$week = $i;
}
}
else {
$week = "1";
}
But that didn't work out too well, I tried using double quotes instead of single around the variables, plus '" and "' to no avail.
Can anyone help with this, or point me towards a good resource on single and double quotes for variables?
Are you all igrnoring the fact that the else if mustn`t be there!?
What you should do is the following
$week = "1";
if ($_POST['week']) {
$week = $_POST['week'];
} else {
for ($i = 1; $i < 7; $i++) {
if ($_POST["user_week" . $i] == "week" . $i) {
$week = $i;
break;
}
}
}
elseif ($_POST['user_week' . $i] == 'week' . $i)
above correction should work

Optimized Logic to find high score

Basically this is related to a squash application where we have 2 scores. One is from winner point of view and another from loser point of view.
eg.
Score1: 11-5,11-5,11-5 (Winner point of view)
Score2: 5-11, 5-11,5-11 (Loser point of view)
Now in my logic i want to find which is the winner score and which is the loser score.
I have written my logic in the below way and it does work. But i want to know if their is any other better/optimized way of writing this.
$high1 = 0;
$high2 = 0;
$score1 = "2-11,5-11,4-11,4-4";
$score2 = "11-2,11-5,11-4,4-4";
$score1Array = explode(",",$score1);
$size = sizeof($score1Array);
for($i = 0; $i < $size; $i++) {
$checkscore1 = explode("-",$score1Array[$i]);
if($checkscore1[0] < $checkscore1[1]) {
$high1++;
}else if($checkscore1[0] > $checkscore1[1]) {
$high2++;
}
}
if($high1 > $high2) {
$winningScore = $score2;
$losingScore = $score1;
}else{
$winningScore = $score1;
$losingScore = $score2;
}
echo $winningscore;
echo $losingscore;
What about something like this:
function is_winning($score) {
$split_scores = preg_split('/(-|,)/', $score);
$wins = $losses = 0;
for($i = 0; $i < count($split_scores) / 2; $i += 2) {
if($split_scores[$i] > $split_scores[$i + 1])
$wins++;
if($split_scores[$i] < $split_scores[$i + 1])
$losses++;
}
return $wins > $losses;
}
Assuming $score is formatted as in your question. You can then use it like this:
$score1 = "2-11,5-11,4-11,4-4";
$score2 = "11-2,11-5,11-4,4-4";
if(is_winning($score1)) {
$winning_score = $score1;
$losing_score = $score2;
} else {
$winning_score = $score2;
$losing_score = $score1;
}
echo $winning_score;
echo $losing_score;
The idea is to split the score into an array where the even numbered indexes have the left score and the odd numbered indexes the right score. We then count the number of wins and the number of losses. If there's more wins then losses then we return true since the score was a winning score. If there's not more wins then losses we simply return false.
This should work
$score1 = "2-11,5-11,4-11,4-4";
$score2 = "11-2,11-5,11-4,4-4";
$l = $r = 0;
$score1_sets_arr = explode(',', $score1);
foreach ($score1_sets_arr as $set_score) {
$set_score_arr = explode('-', $set_score);
if ($set_score_arr[0] > $set_score_arr[1]) {
$l++;
} else {
$r++;
}
}
if ($l > $r) {
$winning_score = $score1;
$losing_score = $score2;
} else {
$winning_score = $score2;
$losing_score = $score1;
}
you can use this :
<?php
$high1 = 0;
$high2 = 0;
$score1 = "2-11,5-11,4-11,4-4";
$score2 = "11-2,11-5,11-4,4-4";
$explode = explode(",",$score1);
for($i=0;$i< sizeof($explode);$i++){
$explode2= explode("-", $explode[$i]);
if($explode2[0] <= $explode2[1]){
echo $explode2[0]."-";
echo $explode2[1]." ";
}
}
echo "<br />";
for($i=0;$i< sizeof($explode);$i++){
$explode2= explode("-", $explode[$i]);
if($explode2[1] >= $explode2[0]){
echo $explode2[1]."-";
echo $explode2[0]." ";
}
}
?>
for Winner point of view, all big score in left,otherwise in right. so u can just detect the first score.
$score1Array = explode(",",$score1);
$checkscore1 = explode("-",$score1Array[$i]);
if($checkscore1[0] < $checkscore1[1]) {
echo $score2;
echo $score1;
}else{
echo $score1;
echo $score2;
}
Fix: above code is wrong,try this:
$score1value = eval(str_replace(",","+",$score1));
$score2value = eval(str_replace(",","+",$score2));
if($score1value < $score2value) {
echo $score2;
echo $score1;
}else{
echo $score1;
echo $score2;
}

Categories