I made a program that lets 6 grades be entered into a form, and then calculates the letter grade and the average. The only problem I'm having is that I can't figure out how to get the form to accept decimals. I tried changing my filter_input statement to sanitize floats, but that doesn't seem to fix the problem. Any thoughts would be appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Grades</title>
<link rel="stylesheet" href="bootstrap.min.css">
<script>
window.onload = () => {
document.getElementById('quiz1').focus();
document.getElementById('quiz1').select();
}
</script>
<style>
input[type="text"] {width: 4em !important; text-align: right; margin-left: .5em; }
ul { list-style-type: none; padding-left: 0; }
</style>
</head>
<body>
<div class="container">
<div class="col-lg-6 mx-auto text-center">
<h1>Enter Quiz Grades</h1>
<form action="." method="post">
<?php
// declare an array to store bowling scores
$quizScores = array();
// declare a variable to be used for the natural counting of the number of games
$numberOfScores = 6;
// declare a variable to be used for array elements - subtract 1 since array elements start at 0
$gamesArrayElements = $numberOfScores - 1;
for ($i = 0; $i <= $gamesArrayElements; $i++){
$quizNumber = $i + 1;
// load values from POST into array elements
if (strlen($_POST['quiz' . $quizNumber]) > 0){
$quizScores[$i] = filter_input(INPUT_POST, 'quiz' . $quizNumber, FILTER_SANITIZE_NUMBER_FLOAT);
}
echo "<div class='form-group form-inline justify-content-center'>\n";
echo "<label for='quiz$quizNumber'>Quiz $quizNumber: </label>\n";
echo "<input type='text' class='form-control' name='quiz$quizNumber' id='quiz$quizNumber' value='$quizScores[$i]'>%\n";
echo "</div>\n";
}
?>
<div class="form-group">
<input type="submit" class="btn btn-secondary" value="Find Average of <?php echo $numberOfScores; ?> Highest Quiz Grades">
Clear
</div>
</form>
<?php
if (count($quizScores) === $numberOfScores){
$total = 0;
echo "<h2>Scores:</h2>\n";
echo "<ul>\n";
// for loop to print array elements and add each score to the total
for ($i = 0; $i <= $gamesArrayElements; $i++){
echo "<li>$quizScores[$i] " . getLetterGrade($quizScores[$i]) . "</li>\n";
$total += $quizScores[$i];
}
echo "</ul>\n";
$average = $total / $numberOfScores;
echo "<h2>Average Score:</h2>\n";
echo "<p>" . number_format($average, 1, .2) . " - " . getLetterGrade($average) . "</p>\n";
} else {
if(count($quizScores) > 0) {
echo "<h2 class='text-danger'>All textboxes should contain grades.</h2>\n";
}
}
?>
</div>
</div>
</body>
</html> ```
I changed number_format($average, 1, .2) to number_format($average, 1) and then I do get the average rounded to one decimal. I also removed the getLetterGrade() function because it is not defined in your code. Finally I change the form action to "", instead of ".", because it didn't work in my test environment.
Perhaps you need to switch on error reporting in PHP? That way you can see what's wrong with your code.
Related
I wanted to create a multiplication table with a custom function and also get the number of rows and columns from the user, and I want if each row was an even number then its field would be red (background) and if it was odd number it would have a green background and i also write some codes but i'm not sure if it's true or not:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<form method="post">
<input type="number" name="rows" placeholder="Rows">
<input type="number" name="columns" placeholder="Columns">
<button type="submit" name="button">
Create
</button>
</form>
<table border="1px">
<?php
if (isset($_POST["button"])) {
$userRows = $_POST["rows"];
$userColumns = $_POST["columns"];
function multiplicationTable($rows, $columns)
{
$zarb = $rows * $columns;
return $zarb;
}
$x = 1;
while ($x <= $userRows) {
echo "<tr>";
$y = 1;
while ($y <= $userColumns) {
if ($x % 2 == 0) {
echo "<td style='background-color: red;'>" . multiplicationTable($x, $y) . "</td>";
} else {
echo "<td style='background-color: green;'>" . multiplicationTable($x, $y) . "</td>";
}
$y++;
}
$x++;
echo "</tr>";
}
}
?>
</table>
</body>
</html>
How about changing the while loops to this:
while ($x <= $userRows) {
echo "<tr>";
$y = 1;
while ($y <= $userColumns) {
$val = multiplicationTable($x, $y);
if ($val % 2 == 0) {
echo "<td style='background-color: red;'>" . $val . "</td>";
} else {
echo "<td style='background-color: green;'>" . $val . "</td>";
}
$y++;
}
$x++;
echo "</tr>";
}
Well, your code looks good. Click here to see how it looks like...
the final result is in this link, and even if some of the numbers are even, they're still displayed in green and i don't know what should i do
https://imgur.com/D1Sweee
So I have to roll 6 six sided die and display their corresponding images. I also have to save up to 10 previous roles and append the new ones each time I roll. I'm so far able to create the array of 6 random numbers and link them to their images. I just need to save that role on page refresh. I've just started learning PHP but from what I've gathered I know sessions are needed. All the examples I looked at didn't help.
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dice Roller</title>
</head>
<style>
h1, input {
margin-left: auto;
margin-right: auto;
}
img {
width: 70px;
height: 70px;
}
</style>
<body>
<h1>Dice Roller</h1>
<input type="button" value="Roll">
<?php
$newRoll = array(rand(1, 6), rand(1, 6), rand(1, 6), rand(1, 6), rand(1, 6), rand(1, 6));
$oldRoll = $newRoll;
foreach($newRoll as $num) {
echo '<img src="img/dicefaces/dice0' . $num . '.png" alt="">';
}
echo "<br>";
foreach($oldRoll as $num) {
echo '<img src="img/dicefaces/dice0' . $num . '.png" alt="">';
}
?>
</body>
</html>
You can use $_SESSION to 'store' the old rolls, following logic might help you on your way:
We store the history in $_SESSION['oldrolls'] allowing us to display up to 10 previous rolls (you can set the number you want to show with $max)
Also created a button to allow for session clear, to start with a clean slate.
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dice Roller</title>
</head>
<style>
table, td, th {
table-layout: fixed;
width: 100%;
border-collapse: collapse;
border: 3px solid black;
text-align: center;
}
h1, input {
margin-left: auto;
margin-right: auto;
}
img {
width: 70px;
height: 70px;
}
</style>
<body>
<h1>Dice Roller</h1>
<!-- allow user to clear the session -->
<form action='' method ='POST'>
<input type="submit" name='clear' value="clear session">
</form>
<!-- submit a roll -->
<br />
<form action='' method ='POST'>
<input type="submit" name='submit' value="Roll">
</form>
<?php
if(isset($_POST['clear'])){
$_SESSION = []; // clear session array
}
if(isset($_POST['submit'])) {
$newRoll = array(rand(1, 6), rand(1, 6), rand(1, 6), rand(1, 6), rand(1, 6), rand(1, 6));
$max = 10; // store up to 10 previous rolls
$count = isset($_SESSION['oldrolls']) ? count($_SESSION['oldrolls']) : 0;
if($count <= $max) {
$_SESSION['oldrolls'][] = $newRoll; // add new
} else {
array_shift($_SESSION['oldrolls']); // remove oldest
$_SESSION['oldrolls'][] = $newRoll; // add new
}
$_SESSION['oldrolls-reverse'] = array_reverse($_SESSION['oldrolls']); // show last first
echo 'Current roll...';
echo '<br />';
foreach ($newRoll as $num) {
echo $num;
echo '<br />';
}
echo "<br>";
echo 'previous rolls...';
echo '<br />';
echo '<table>';
foreach ($_SESSION['oldrolls-reverse'] as $key => $num) {
if($key === 0) continue;
echo '<tr>';
foreach($num as $roll) {
echo '<td>' . $roll . '</td>';
}
echo '</tr>';
}
echo '</table>';
}
?>
</body>
</html>
This Question is a bit long and I have edited too much to reduce my code but I hope anyone can help me out please!
I'm working on a Math test in times table project with php which will ask the user to enter his name and then ask him 10 questions like "2 x 2 = ?" giving four buttons to choose an answer and then after answering 10 questions the user will be redirected to result.php page which will show the result and here is what I wrote so far in homePage.php:
<?php
session_start();
if (isset($_POST['submit']) ) {
$_SESSION['QuestionNumber'] = 1;
$_SESSION['CorrectAnswers'] = 0;
$_SESSION['QuestionsAsnwered'] = 0;
$_SESSION['QuestionsAnswered'] = 0;
header("location: MathTest.php");
}
?>
<!DOCTYPE html>
<html>
<body>
<h1 align="center">Math Test</h1>
<form method="POST" action="">
<div style="text-align: center;">
<input type="submit" name="submit" value="Begin Test"">
</div>
</form>
</body>
</html>
and in MathTest.php which contains the problem:
<?php
session_start();
//just controlling user answer no problem here
if (isset($_POST[$_SESSION['UserAnswer']])) {
if ($_SESSION['QuestionNumber'] == 10) {
header("location: result.php");
}
if ($_SESSION['UserAnswer'] == $_SESSION['CorrectAnswer']) {
$_SESSION['QuestionNumber'] += 1;
$_SESSION['CorrectAnswers'] += 1;
$_SESSION['QuestionsAnswered'] += 1;
QuestionGenerator();
} else {
$_SESSION['QuestionNumber'] += 1;
$_SESSION['QuestionsAnswered'] += 1;
QuestionGenerator();
}
}
//I think that my problem(written down) is here
function QuestionGenerator(){
$rnd1 = rand(1, 12);
$rnd2 = rand(2, 12);
$CorrectAnswer = $rnd1 * $rnd2;
$WrongAnswer1 = $CorrectAnswer - 2;
$WrongAnswer2 = $CorrectAnswer + 2;
$WrongAnswer3 = $CorrectAnswer + 4;
$_SESSION['rnd1'] = $rnd1;
$_SESSION['rnd2'] = $rnd2;
$_SESSION['CorrectAnswer'] = $CorrectAnswer;
$_SESSION['WrongAnswer1'] = $WrongAnswer1;
$_SESSION['WrongAnswer2'] = $WrongAnswer2;
$_SESSION['WrongAnswer3'] = $WrongAnswer3;
$_SESSION['AnswersArray'] = array($_SESSION['CorrectAnswer'], $_SESSION['WrongAnswer1'], $_SESSION['WrongAnswer2'], $_SESSION['WrongAnswer3']);
}
function EchoAnswers($array) {
shuffle($array);
echo "<form method='POST' action='' ";
foreach ($array as $_SESSION['UserAnswer']) {
echo "<button><input style='width: 200px; height: 100px; font-size: 75px;' type='submit' name='" . $_SESSION['UserAnswer'] . "' value='" . $_SESSION['UserAnswer'] . "' ></button";
}
echo "</form>";
}
?>
<!DOCTYPE html>
<html>
<body>
<?php echo "<h1 align='center' style='font-size: 75px;'>Question " . $_SESSION['QuestionNumber'] . " of 10</h1>"; ?>
<h2 align="center" style="font-size: 60px"><?php echo $_SESSION['rnd1'] . " X " . $_SESSION['rnd2'] . " = ?" ?></h2>
<div align="center">
<?php EchoAnswers($_SESSION['AnswersArray']) ?>
</div>
</body>
</html>
the problem is when I click on any button it will only shuffle the answers but if I press the last button it will work full functionally
The problem I had was that there is 4 submit buttons each with different name tag so the session will only store the last input button and will make it functional but for the others it will only refresh the page with no different because they are not being controlled by php code so to solve this problem I only changed the EchoAnswers function like this:
function EchoAnswers($array) {
shuffle($array);
echo "<form method='POST' action='' ";
foreach ($array as $_SESSION['UserAnswer']) {
echo "<button><input style='margin: 10px; border: 3px solid black; background-color: lightblue; width: 200px; height: 100px; font-size: 75px;' type='submit' name='UserAnswer' value='" . $_SESSION['UserAnswer'] . "' ></button";
}
echo "</form>";
}
the name tag was also set to $_SESSION['UserAnswer'] so I changed this part to a normal name and I also changed the php code like this:
if (isset($_POST['UserAnswer'])) {
if ($_SESSION['QuestionNumber'] == 10) {
header("location: result.php");
}
if ($_SESSION['UserAnswer'] == $_SESSION['CorrectAnswer']) {
$_SESSION['QuestionNumber'] += 1;
$_SESSION['CorrectAnswers'] += 1;
$_SESSION['QuestionsAnswered'] += 1;
QuestionGenerator();
} else {
$_SESSION['QuestionNumber'] += 1;
$_SESSION['QuestionsAnswered'] += 1;
QuestionGenerator();
}
}
the part that I have changed in php code is isset($_POST['UserAnswer']) because UserAnswer was set to $_SESSION['UserAnswer'] instead of normal name in the name tag.
<!DOCTYPE html>
<html lang="en">
<head>
<h1>Table Generator</h1>
</head>
<body>
<center>Refresh</center>
<?php
$rows = (isset($_POST['rows']) ? $_POST['rows'] : null);
$cols = (isset($_POST['cols']) ? $_POST['cols'] : null);
$highlight = (isset($_POST['highlight']) ? $_POST['highlight'] : null);
if ($rows == "")
{
$rows = 10;
}
if ($cols == "")
{
$cols = 10;
}
if ($highlight == "")
{
$highlight = 5;
}
?>
<form method="post">
ROWS <input type="text" name="rows" value = "<?php echo $rows;?>" />
COLUMNS <input type="text" name="cols" value = "<?php echo $cols;?>" />
HIGHLIGHT <input type = "text" name = "highlight" value = "<?php echo $highlight;?>" /><br>
<input type="submit" value="Generate">
</form>
<?php
if(isset($_POST['rows']))
{
$randnumber = rand(0,100);
$rows = $_POST['rows'];
$cols = $_POST['cols'];
$highlight = $_POST['highlight'];
echo '<table border="1" align = "center">';
if (is_numeric($rows) and is_numeric($cols) and is_numeric($highlight))
{
if ($randnumber % 2 == 0)
{
echo '<center>The first number is <div class = "red">even</div></center>';
}
else
{
echo '<center>The first number is <div class = "green">odd</div></center>';
}
for($row = 1; $row <= $rows; $row++)
{
echo '<tr style = "background-color:green">';
for($col = 1; $col <= $cols; $col++)
{
if ($randnumber % $highlight == 0)
{
echo '<td style = "background-color: red">';
echo $randnumber;
$randnumber++;
echo '</td>';
}
else
{
echo '<td>';
echo $randnumber;
$randnumber++;
echo '</td>';
}
}
echo '</tr>';
}
echo '</table>';
}
else
{
echo "<center>Rows / Columns / Highlight must ALL be INTEGER values. Re-enter correct value(s).</center>";
}
echo '<pre><center>';
print_r($_POST);
echo '</center></pre>';
}
?>
<style type ="text/css">
h1 {
color: grey;
text-align:center;
}
form {
text-align: center;
padding-bottom: 20px;
}
a:link {
text-decoration: none;
}
.red {
color: red;
}
.green {
color: green;
}
</style>
</body>
</html>
So. I have this PHP code to generate a table based off the user's input and I recently ran into a problem I cant figure out how to fix.
It was working perfectly fine but now whenever I use the Refresh link it resets the entire page to default (i.e. default textbox values instead of keeping the current ones, removing the table).
So, I have 2 questions. How would I keep the data on refresh (with $_POST being used) and how to display the table with the default values when the page first loads.
Refresh
Clicking it will trigger browser's reload mechanism and you'll be asked to resubmit the form action, it will allow you to keep POST data.
You need to re-create the post if you want to keep the parameters. Can be done pretty eaily by looping thru the array.
<form method='POST' id='refresh' action='<?php echo $_SERVER['PHP_SELF']; ?>'>
<?php foreach($_POST as $k=>$v): ?>
<input type='hidden' name='<?php echo $k; ?>' value='<?php echo $v; ?>' />
<?php endforeach; ?>
<a href='#' onclick='document.getElementById("refresh").submit(); return false;'>refresh</a>
</form>
Note: This is a little longer than the other answer, but will not prompt to resend post data.
I've downloaded this tutorial http://megarush.net/5-star-rating-system-with-php-mysql-jquery-and-ajax/ but I'm getting these errors:
Notice: Undefined variable: rat in C:\xampp\htdocs\rating\rating.php on line 37
Notice: Undefined variable: v in C:\xampp\htdocs\rating\rating.php on line 41
<?php
include("settings.php");
connect();
$ids=array(1,2,3);
?>
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<link rel="stylesheet" href="rating.css" />
<script type="text/javascript" src="rating.js"></script>
</head>
<body>
<?php
for($i=0;$i<count($ids);$i++)
{
$rating_tableName = 'ratings';
$id=$ids[$i];
$q="SELECT total_votes, total_value FROM $rating_tableName WHERE id=$id";
$r=mysql_query($q);
if(!$r) echo mysql_error();
while($row=mysql_fetch_array($r))
{
$v=$row['total_votes'];
$tv=$row['total_value'];
$rat=$tv/$v;
}
$j=$i+1;
$id=$ids[$i];
echo'<div class="product">
Rate Item '.$j.'
<div id="rating_'.$id.'" class="ratings">';
for($k=1;$k<6;$k++){
if($rat+0.5>$k)$class="star_".$k." ratings_stars ratings_vote";
else $class="star_".$k." ratings_stars ratings_blank";
echo '<div class="'.$class.'"></div>';
}
echo' <div class="total_votes"><p class="voted"> Rating: <strong>'.#number_format($rat).'</strong>/5 ('.$v. ' vote(s) cast)
</div>
</div></div>';}
?>
</body></html>
$rat and $v are being defined within the scope of your while loop.
If you declare them globally (outside the loop), the rest of your code will recognize them.
$rat = 0;
$v = 1;
while($row=mysql_fetch_array($r))
{
$v=$row['total_votes'];
$tv=$row['total_value'];
$rat=$tv/$v;
}
See here:
http://bgallz.org/988/javascript-php-star-rating-script/
This combines a Javascript code that generated the URL for the different ratings given as well as the change in display for the stars before and after a rating is given.
An overlay DIV is displayed after the rating is given so that no immediate ratings can be given by the same. It also stores the user's IP address with the rating submission to prevent multiple ratings from one user.
This is a simple and easy to use script with just Javascript and PHP for star rating.
The problem is because of scoping of those variables. When you are trying to echo those variables outside the while loop; PHP can not find the varables as they were created (and assigned) inside the loop. To solve this, just assign a blank value to both variables outside too:
if(!$r) echo mysql_error();
$rat = 0;
$v = 1; // In case there are no records.
while($row=mysql_fetch_array($r))
{
$v = $row['total_votes'];
$tv = $row['total_value'];
$rat = $tv/$v;
}
Add this at line at beginning to nide notice error in your code .
error_reporting(E_ALL ^ E_NOTICE);
Most of time notice error do not affect the program.
In case if your votes are not recording then delete your cookies and try to vote from different IP address .This script has a feature to not accept votes from same ip or vistitor to avoid multiple votes by same users on same product.
var cname=document.getElementById(id).className;
var ab=document.getElementById(id+"_hidden").value;
document.getElementById(cname+"rating").innerHTML=ab;
for(var i=ab;i>=1;i--)
{
document.getElementById(cname+i).src="star2.png";
}
var id=parseInt(ab)+1;
for(var j=id;j<=5;j++)
{
document.getElementById(cname+j).src="star1.png";
}
Code from http://talkerscode.com/webtricks/star-rating-system-using-php-and-javascript.php
<style>
.star {
font-size: x-large;
width: 50px;
display: inline-block;
color: gray;
}
.star:last-child {
margin-right: 0;
}
.star:before {
content:'\2605';
}
.star.on {
color: red;
}
.star.half:after {
content:'\2605';
color: red;
position: absolute;
margin-left: -20px;
width: 10px;
overflow: hidden;
}
</style>
<div class="stars">
<?php
$enable = 5.5; //enter how many stars to enable
$max_stars = 6; //enter maximum no.of stars
$star_rate = is_int($enable) ? 1 : 0;
for ($i = 1; $i <= $max_stars; $i++){ ?>
<?php if(round($enable) == $i && !$star_rate) { ?>
<span class="<?php echo 'star half'; ?>"></span>
<?php } elseif(round($enable) >= $i) { ?>
<span class="<?php echo 'star on'; ?>"></span>
<?php } else { ?>
<span class="<?php echo 'star'; ?>"></span>
<?php }
}?>
</div>