PHP Countdown that resets - php

I have a coding matter i need your aid with. I have attempted to solve it for a few days, but all it results in is frustration. I haven't found any existing examples or help on the internet, and all i have done so far is staring at my code, my mind blank.
I need a countdown to 17:00 (5 PM) each day, echoing a message saying that a certain amount of time is remaining until 17:00. After 17:00, i want to echo another message. Then, the timer needs to reset after 23.59. How can i do this with PHP?
Any help would be appreciated! Below is the code i already have, but i don't think any part of it would affect what i need help with:
<?php
session_start();
#ADD ITEM
if( isset( $_POST['newitem'] ) ){
$_SESSION['todo'][]=$_POST['newitem'];
}
#REMOVE ITEM
if( isset( $_POST['remove_id'] ) ){
$id = $_POST['remove_id'];
unset( $_SESSION['todo'][$id] );
}
?>
<html>
<head>
<title></title>
</head>
<body>
<?php
$i = 0;
echo "<h1>To Do</h1>";
#SUBMIT
echo "
<form action='' method='post'>
<input type='text' name='newitem'>
<input type='submit'>
</form>
";
foreach( $_SESSION['todo'] as $id => $item ){
$i++;
#REMOVE
echo "
<form action='' method='post'>
<input type ='hidden' name='remove_id' value='$id'>
<input type='submit' value='-'>
$item
</form>";
}
echo $i;
#CHANGE BACKGROUND COLOR DEPENDING ON DAY
$day=date("l");
switch($day) {
case 'Monday':
$bg_color = "red";
break;
case 'Tuesday':
$bg_color = "blue";
break;
case 'Wednesday':
$bg_color = "purple";
break;
case 'Thursday':
$bg_color = "gray";
break;
case 'Friday':
$bg_color = "yellow";
break;
case 'Saturday':
$bg_color = "green";
break;
case 'Sunday':
default:
$bg_color = "beige";
break;
}
echo "<body style='background-color:$bg_color'>";
?>
</body>
</html>

I need a countdown to 17:00 (5 PM) each day, echoing a message saying
that a certain amount of time is remaining until 17:00. After 17:00, i
want to echo another message. Then, the timer needs to reset after
23.59. How can i do this with PHP?
if(date("H") < "17") echo "There are " . (16 - date("H")) . " hours and " . (60 - date("i")) . " minutes left until 17:00.";
else if(date("H") == "17" && date("i") == "00") echo "It is 17:00.";
else echo "17:00 is over for today.";

Related

PHP: How to use switch statement to retrieve radio button values

I'm working on a homework assignment while learning PHP for the first time. Everything is working, except for my switch statement. My professor is asking-
"Modify index.php
Get the selected value from the "calculate" radio button you created
Add a switch statement to set values for:
only the average calculation if the user selected the "average" radio button
only the total calculation if the user selected the "total" radio button
both the average and total if the user selected the "both" button."
I'd like to provide my entire index.php file in case it's important to see everything-
<?php
//set default values to be used when page first loads
$scores = array();
$scores[0] = 70;
$scores[1] = 80;
$scores[2] = 90;
$scores_string = '';
$score_total = 0;
$score_average = 0;
$max_rolls = 0;
$average_rolls = 0;
$score_total_f = '';
$score_average_f = '';
//take action based on variable in POST array
$action = filter_input(INPUT_POST, 'action');
switch ($action) {
case 'process_scores':
$scores = $_POST['scores'];
// validate the scores
$is_valid = true;
for ($i = 0; $i < count($scores); $i++) {
if (empty($scores[$i]) || !is_numeric($scores[$i])) {
$scores_string = 'You must enter three valid numbers for scores.';
$is_valid = false;
break;
}
}
if (!$is_valid) {
break;
}
// process the scores
$score_total = 0;
foreach ($scores as $s) {
$scores_string .= $s . '|';
$score_total += $s;
}
$scores_string = substr($scores_string, 0, strlen($scores_string)-1);
// calculate the average
$score_average = $score_total / count($scores);
// format the total and average
$score_total_f = number_format($score_total, 2);
$score_average_f = number_format($score_average, 2);
$calculate = filter_input(INPUT_POST, 'calculate');
switch($calculate) {
case "average":
$message_average = $score_average_f;
break;
case "total":
$message_total = $score_total_f;
break;
case "both":
$message_average = $score_average_f;
$message_total = $score_total_f;
break;
default: die("Invalid type");
}
break;
case 'process_rolls':
$number_to_roll = filter_input(INPUT_POST, 'number_to_roll',
FILTER_VALIDATE_INT);
$total = 0;
$max_rolls = -INF;
for ($count = 0; $count < 10000; $count++) {
$rolls = 1;
while (mt_rand(1, 6) != $number_to_roll) {
$rolls++;
}
$total += $rolls;
$max_rolls = max($rolls, $max_rolls);
}
$average_rolls = $total / $count;
break;
}
include 'loop_tester.php';
?>
Also, here is part of the other file where I had to create radio buttons-
<h3>What do you want to do?</h3>
<input type="radio" name="calculate" value="average" checked> Average<br>
<input type="radio" name="calculate" value="total"> Total<br>
<input type="radio" name="calculate" value="both"> Both<br>
<label>Scores:</label>
<span><?php echo htmlspecialchars($scores_string); ?></span><br>
<label>Score Total:</label>
<span><?php echo $message_total; ?></span><br>
<label>Average Score:</label>
<span><?php echo $message_average; ?></span><br>
</form>
Thank you!
Again, everything is working fine when I test in XAMPP, just not the switch statement. I get no output of any kind.
EDIT: Disregard my original answer, I tested out your original syntax and it seems to work fine. Sorry, that was a mistake on my part, though I'd still say the new code is more elegant.
There seems to be an issue with a misplaced break; - Here is a full working code for to 'process_scores' case:
case 'process_scores':
$scores = $_POST['scores'];
// validate the scores
$is_valid = true;
for ($i = 0; $i < count($scores); $i++) {
if (empty($scores[$i]) || !is_numeric($scores[$i])) {
$scores_string = 'You must enter three valid numbers for scores.';
$is_valid = false;
break;
}
}
if (!$is_valid) {
break;
}
// process the scores
$score_total = 0;
foreach ($scores as $s) {
$scores_string .= $s . '|';
$score_total += $s;
}
$scores_string = substr($scores_string, 0, strlen($scores_string)-1);
// calculate the average
$score_average = $score_total / count($scores);
// format the total and average
$score_total_f = number_format($score_total, 2);
$score_average_f = number_format($score_average, 2);
$calculate = filter_input(INPUT_POST, 'calculate');
$score_average_f = number_format($score_average, 2);
$score_total_f = number_format($score_total, 2);
switch($calculate) {
case "average":
echo "Average: " . $score_average_f;
break;
case "total":
echo "Total: " . $score_total_f;
break;
case "both":
echo "Average: " . $score_average_f . "<br />";
echo "Total: " . $score_total_f;
break;
default: die("Invalid type");
}
break;
I'm not sure about other the other part of your code, but I tested this and got the intended results. If you still see nothing, check what's in your $_POST variables. Also as a general advice for debugging: in a situation like this, just go through your code and echo stuff out inside and outside of every loop or function you believe your code should reach, to see where it gets derailed. It may not sound too professional, but it sure gets the job done.
I'm doing the same exercise. You need to define your variables before all the code runs.
$scores_string = '';
$score_total = 0;
$score_average = 0;
$max_rolls = 0;
$average_rolls = 0;
$message_average = 0;
$message_total = 0;
After I defined variables, $message_average and $message_total, everything worked fine.

It always says Correct! What did I do wrong?

$number1 = mt_rand(1,9);
$number2 = mt_rand(1,9);
$total = $number1 * $number2;
echo "<form method='post'>";
echo $number1 . " x " . $number2 . " = <input type='number' name='num1' required /><br>";
echo "<input type='submit' value='submit!' name='done'>";
echo "</form>";
if (isset($_POST['done'])) {
if (isset($_POST['num1']) == $total) {
echo "Correct!";
} else {
echo "Wrong!";
}
}
It always says Correct! And I dont know why ( im a beginner ), I just want to check if num1 is equal to $total
You have many problems in your code :
you must first check if the post is submit then if its wrong type the form
if (isset($_POST['done'])) {
//your code
}
else {
//your form
}
save $total in session to reuse it when the form submit, in your case $total have different value every time
isset() return true or false you can't comparison true or false with integer value if you want to use isset your code must be like this:
if(isset($_POST['num1']) && $_POST['num1'] == $total) {
}
You're comparing isset($var) to $total. They're both truthy so the condition is always true as long as 'num1' is defined in your POST data.
Maybe you should do something like :
isset($_POST['num1']) && $_POST['num1'] == $total
You should also probably cast 'num1' to a number
As said by Tom Udding, every time you refresh the page it calls ALL of that code again, so number1 and number2 are being randomly selected again.
Your current code has no way of saving the previous variable values. An unconventional way would be to add a hidden form field with the answer to the question, like below:
<?php
if (isset($_POST['done']) && isset($_POST['num1']))
{
//Get answer from form.
$total = $_POST['answer'];
if ($_POST['num1'] == $total)
{
echo "Correct!";
}
else
{
echo "Wrong!";
}
}
$number1 = mt_rand(1, 9);
$number2 = mt_rand(1, 9);
$total = $number1 * $number2;
echo "<form method='post'>";
echo $number1 . " x " . $number2 . " = <input type='number' name='num1' required /><br>";
//Added hidden form with answer.
echo "<input type='number' hidden name='answer' value='$total' />";
echo "<input type='submit' value='submit!' name='done'>";
echo "</form>";
?>
HOWEVER...
In a realistic rich web application, you wouldn't put your answer in your form for users to see, this is where you can use sessions to track your user's information as they traverse (or in your case refresh) your page.
So a more practical answer to your question would be the following:
<?php
session_start();
if (isset($_POST['done']) && isset($_POST['num1']))
{
$answer = $_SESSION['answer'];
if ($_POST['num1'] == $answer)
{
echo "Correct!";
} else
{
echo "Wrong!";
}
}
$number1 = mt_rand(1, 9);
$number2 = mt_rand(1, 9);
$total = $number1 * $number2;
$_SESSION['answer'] = $total;
echo "<form method='post'>";
echo $number1 . " x " . $number2 . " = <input type='number' name='num1' required /><br>";
echo "<input type='number' hidden name='answer' value='$total' />";
echo "<input type='submit' value='submit!' name='done'>";
echo "</form>";
?>

Why does this block of code result in a blank space?

My goal is to subtract the two times and then generate a logged in checker from there.
What I need to know, is if I have correctly subtracted the two times in minutes.
PHP Version: 7.0
Time is entered into the DB using NOW() and shows as (Example: 2016-07-23 15:01:34)
For some reason, where this code is included in HTML, is just blank.
Code (everything is defined higher up in the code) :
<?php
include ('../includes/connection.php');
include ('../scripts/functions.php');
$getOnlineAdmins = $handler->prepare('SELECT * FROM Admins WHERE AdminLevel >= :al AND Status= :stat');
$statn = 1;
$aln = 1;
$getOnlineAdmins->bindParam(':al', $aln);
$getOnlineAdmins->bindParam(':stat', $statn);
$getOnlineAdmins->execute();
echo "
<table class='table-fill'>
<thead>
<tr>
<th class='text-left' style='padding-left: 12px; padding-right: 12px;';></th>
</tr>
</thead>
<tbody class='table-hover'>";
if ($getOnlineAdmins->rowCount() >=1){
echo ("These is one or more rows.");
while ($results = $getOnlineAdmins->fetch()){
if((strtotime($results['LastVisited']) + 900) >= time()){
echo ("Time requirement met.");
switch ($results['AdminLevel']) {
case 3:
$rank = 'In-Training/Intern';
break;
case 6:
$rank = 'Community Moderator';
break;
case 9:
$rank = 'Senior Moderator';
break;
case 12:
$rank = 'Supervisor';
break;
case 15:
$rank = 'Administrator';
break;
case 18:
$rank = 'Senior Administrator';
break;
case 21:
$rank = 'Staff Advisor';
break;
case 24:
$rank = 'Engineer';
break;
case 27:
$rank = 'Vice Chairman';
break;
case 30:
$rank = 'Chairman';
break;
case 33:
$rank = 'Website Engineer';
break;
default:
$rank = 'Unknown';
break;
}
echo "<tr>";
echo "<td>" . $results['Username'] . " - " . $rank . "</td>";
} else {
echo "<tr><td>{$results['Username']} – $rank</td>";
}
}
}else{
echo "<tr><td>There are no staff members online.</td>";
}
echo " </tbody>
</table>";
?>
As far as I understand it, now() is not getting the current time as you expect it to. See this question for what I believe to be the root of your misunderstanding.
Assuming $results['LastVisited'] is in the format 2016-07-23 14:11:02 – you could convert it to a UNIX timestamp with strtotime.
So if the time 15 minutes ago is less than or equal to your last visited time:
if (strtotime('-15 minutes') <= strtotime($results['LastVisited'])) {}
Alternative format with time() – that you would use instead of the MySQL equivalent UNIX_TIMESTAMP():
if ((time() - 900) <= strtotime($results['LastVisited'])) {}

PHP how to save values cookies/sessions [duplicate]

This question already has an answer here:
PHP sessions not working for game
(1 answer)
Closed 7 years ago.
I am making a simple game using PHP.
I need to store certain things like what round of the game is going on and what the total is etc and save this data and have access to it later(on another page or when I come back to this page)
I tried using sessions but this isn't working out for me.
Can I do this using cookies?
This is my first time using PHP.
Here is my code if it helps to understand:
<form method="get" action= "skunk.php">
<h1>PLAY SKUNK</h1>
ROLL AGAIN? <br>
yes<input type="radio" name="role2" value="yes"/>
no<input type="radio" name="role2" value="no"/>
<br>
<input type="submit"/>
</form>
<?php
session_start();
$_SESSION["s"] = array(0);
$_SESSION["k1"] =array(0);
$_SESSION["u"] = array(0);
$_SESSION["n"] = array(0);
$_SESSION["k2"] = array(0);
$rand = 0;
$rand2 = 0;
$_SESSION["round"] = 1;
if($_REQUEST["role2"] == "yes"){
$rand = rand (1, 6);
$rand2 = rand(1, 6);
if($rand == 1 and $rand ==1){
switch ($_SESSION["round"]) {
case 1:
$_SESSION["s"] = array(0);
break;
case 2:
$_SESSION["s"] = array(0);
$_SESSION["k1"] =array(0);
break;
case 3:
$_SESSION["s"] = array(0);
$_SESSION["k1"] =array(0);
$_SESSION["u"] = array(0);
break;
case 4:
$_SESSION["s"] = array(0);
$_SESSION["k1"] =array(0);
$_SESSION["u"] = array(0);
$_SESSION["n"] = array(0);
break;
case 5:
$_SESSION["s"] = array(0);
$_SESSION["k1"] =array(0);
$_SESSION["u"] = array(0);
$_SESSION["n"] = array(0);
$_SESSION["k2"] = array(0);
break;
}
}
if($rand > 1 and $rand2 > 1) {
switch ($_SESSION["round"]) {
case 1:
array_push($_SESSION["s"], $rand, $rand2);
break;
case 2:
array_push($_SESSION["k1"], $rand, $rand2);
break;
case 3:
array_push($_SESSION["u"], $rand, $rand2);
break;
case 4:
array_push($_SESSION["n"], $rand, $rand2);
break;
case 5:
array_push($_SESSION["k2"], $rand, $rand2);
break;
}
$_SESSION["round"]++;
}
if($_SESSION["round"] > 5){
session_destroy();
}
echo "you rolled: " . $rand . "\n";
echo "you rolled: " . $rand2;
}
?>
<table style="width:100%" border="1" >
<tr>
<td>S</td>
<td>K</td>
<td>U</td>
<td>N</td>
<td>K</td>
</tr>
</table>
<table style="width:100%" border="1" >
<tr>
<td><?php echo array_sum($_SESSION["s"]); ?></td>
<td><?php echo array_sum($_SESSION["k1"]); ?></td>
<td><?php echo array_sum($_SESSION["u"]); ?></td>
<td><?php echo array_sum($_SESSION["n"]); ?></td>
<td><?php echo array_sum($_SESSION["k2"]); ?></td>
</tr>
</table>
I would use session only for user log status check, and store all other data into db it would make it easier to manage and more consistent.

PHP Change background on Time

So, For school i have to make PHP show the time, And for example when it is 12:00 the background is a afternoon one, and on 02:00 it is a Night one. This is my code:
<body>
<?php
<div class="tijd">
date_default_timezone_set('GMT+1');
echo date('h:i');
$Tijd = date('h');
if ($Tijd > 12 || $Tijd <17') {
echo '<div class="Middag"> </div>';
}
if ($Tijd > 12 || $Tijd <17') {
echo '<div class="Avond"> </div>';
}
if ($Tijd >= '22') {
echo '<div class="Nacht"> </div>';
}
if ($Tijd >= '6') {
echo '<div class="Ochtend"> </div>';
}
echo('Dit is een test...')
?>
</div>
</body>
</html>
But, What is not working here? On the webpage it shows the time correctly but it doesnt show the background. It is also not working while i do a background color or something so i know it is not only the background color. I tried also to make a background in PHP but i kind of failed at that.
You should use if, else if:
if ($Tijd > 12 || $Tijd <17) {
echo '<div class="Middag"> </div>';
} else if ($Tijd > 12 || $Tijd <17) {
echo '<div class="Avond"> </div>';
} else if ($Tijd >= 22) {
echo '<div class="Nacht"> </div>';
} else if ($Tijd >= 6) {
echo '<div class="Ochtend"> </div>';
}
Having said that, your first two test conditions are exactly the same, so you should look at that too
(this should be a comment but its a bit long).
In addition to Marc B's comment, there's random quotes all over the place - don't quote numeric values when you're trying to do a numeric comparison. You're mixing HTML and PHP -
<?php
<div class="tijd">
This should be causing your code to throw big errors. If you're not seeing these errors then you need to investigate why.
And the way you are running multiple if statements is messy. You could use if...else if...else if ...else, but if you use a switch statement your code will be much clearer:
switch((integer)$Tijd) {
case 13:
case 14:
case 15:
case 16:
echo '<div class="Middag"> </div>';
break;
case 22:
case 23:
echo '<div class="Nacht"> </div>';
break;
default:
echo '<div class="Avond"> </div>';
break;
}
As you can see - there are gaps here which are not described by your original code.
<?php
$hour = date('H'); //H is for 24 hours interval
if ($hour > 4 && $hour < 6) {
$class = 'earlier-morning';
} elseif ($hour >=6 && $hour <=11) {
$class = 'morning';
} elseif ($hour >=11 && $hour < 15) {
$class = 'midday';
} elseif($hour >= 15 && $hour < 19) {
$class = 'day';
} elseif ($hour >= 19 && $hour < 22) {
$class = 'evening';
//the only one case left - hours between 22 and 4
} else {
$class = 'night';
}
echo sprintf('<div class="%s"></div>', $class);
The trick here is elseif
So only ONE condition will always work here.
P.S. I believe that extra quotes in your example is a typo ;-)

Categories