Keep Page Data on Refresh With $_POST - php

<!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.

Related

How to fix an array of inputs and display it correctly

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.

CSS, PHP, mySQL Loop - change td colour depending on variable

Having an issue with assigning a td style class, depending on a variable from mySQL. I have a field called 'Avail' so when a seat is available, the seat should turn green. However, nothing is happening so far when I run it.
Have created the simple classes on the same html sheet but it doesn't seem to apply to any of the data.
CSS Class Definitions >>
<style>
.available {
background-color: green;
}
.unavailable {
background-color: red;
}
</style>
Code to show when style will be applied >>
<table>
<tr>
<th>Seats</th>
<tr>
<tr>
<?php
$c = 0; // Our counter
foreach($res as $row) {
$Avail = 'Avail';
$seatColour = null;
if($Avail == 0)
{
$seatColour = '.available';
} else
{
$seatColour = '.unavailable';
}
if($c % 20 == 0 && $c != 0) // If $c is divisible by $n...
{
// New row
echo '</tr><tr>';
}
$c++;
?>
<td style="$seatColour">
<form method="POST" name="Seating" action="SWG.php">
<?php echo $row['Seat']; ?> <?php echo $row['Avail']; ?>
<input type="checkbox" name="Seat[]" value="<?php echo $row['Seat'];?>"/>
</td>
<?php
}
?>
</tr>
</table>
Would really appreciate it if someone could point out where I'm wrong / how I'm assigning it incorrectly.
There seem to be several issues with your code:
$Avail = 'Avail';
$seatColour = null;
if($Avail == 0)
In the above code, you assign $Avail a string, and then you check whether it's zero. I'm assuming this is not deliberate. Maybe you want to assign the database value here (instead of a string)?
$seatColour = '.available';
You probably want to do $seatColour = "available". We're not in jQuery so no need for the dot.
td style="$seatColour"
You probably want to do <td class="<?php echo $seatColour ?>"> over here
Use class attribute instead of style in td and remove . from $seatColour as follows:
<table>
<tr>
<th>Seats</th>
<tr>
<tr>
<?php
$c = 0; // Our counter
foreach($res as $row) {
$Avail = 'Avail';
$seatColour = null;
if($Avail == 0)
{
$seatColour = 'available';
} else {
$seatColour = 'unavailable';
}
if($c % 20 == 0 && $c != 0) // If $c is divisible by $n...
{
// New row
echo '</tr><tr>';
}
$c++;
?>
<td class="$seatColour"><form method="POST" name="Seating" action="SWG.php">
<?php echo $row['Seat']; ?> <?php echo $row['Avail']; ?>
<input type="checkbox" name="Seat[]" value="<?php echo $row['Seat'];?>"/>
</td>
<?php } ?>
</tr>
</table>
instead of null try -1 .
or you put name/value for th.

PHP page with dropdown

I have a php page that updates scores in a MySQL database. Currently the page displays the value from the db. I want to change that to a dropdown list (0-9) that will then update the database. I'm a newbie and can't figure this out. Your help would be greatly appreciated. Here is what I have so far. I have truncated the code;
<h1>UPDATE SCORES</h1>
<form method="post" action="add_scores.php" >
<table width="60%" cellpadding="15" style="font-family: verdana, arial; border: #FFCC99 1px solid">
<tr>
<td height="28" colspan="24" align="center" style="font-size: 44px">
<strong><li>1st Quarter:</li></strong><br>
<strong><font color="#DB2824">NFC: </font></strong><input size="4" maxlength="1" name="away_first" value="<?php echo $record['away_first'];?>"/>
<strong><font color="#232B85">AFC: </font></strong><input size="1" maxlength="1" name="home_first" value="<?php echo $record['home_first'];?>"/>
<br><br>
didn't test it, but this function should generate the code for you:
<?php
function generateSelect($name, $value) {
$str = "<select name='$name'>";
foreach(\range(0,9) as $i) {
$selected = $i == $value ? 'selected' : '';
$str .= "<option value='$i' $selected>$i</option>";
}
$str .= "</select>";
return $str;
}
Replace your inputs with something like this:
<select name="away_first">
<?php
for ($i = 0; $i <= 9; $i++) {
if ($record['away_first'] == $i) {
echo '<option selected>' . $i . '</option>';
} else {
echo '<option>' . $i . '</option>';
}
}
?>
</select>
This is just an example, nothing I've tested.
If you want the form to autopost you could just add a simple onchange-listener to it, either inline or in a script block/file.

create table of checkboxes with select all option

I am creating a table of checkboxes, where the first column will contain checkboxes that can check / uncheck the current row.
This is my code so far, which is not working.
<!DOCTYPE html>
<html>
<head>
<script language="JavaScript">
function toggle(source, $id) {
checkboxes = document.getElementsByName($id);
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
</head>
<body>
<?php
echo "<table>";
for ($x = 0; $x < 3; $x++) {
$id = $x;
echo "
<tr>";
echo "
<td>";
echo '<input type="checkbox" onClick="toggle(this, $id)"/> Toggle All';
echo '
</td>
';
for ($y = 0; $y < 7; $y++){
echo "
<td>";
echo '<input type="checkbox" name=$id value="bar1"> Bar 1<br/>';
echo '
</td>
';
}
echo "
</tr>
";
}
echo "</table>";
?>
</body>
</html>
I am aware that the code might contain several errors and am trying to find them. In the meantime, i would appreciate any suggestions.
try this code
<!DOCTYPE html>
<html>
<head>
// your java script code for toggle is working only change is used id not $id.
<script language="JavaScript">
function toggle(source, id) {
checkboxes = document.getElementsByName(id);
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
</head>
<body>
<?php
echo "<table>";
for ($x = 0; $x < 3; $x++) {
$id = $x;
echo "<tr>";
echo "<td>";
echo '<input type="checkbox" onClick="toggle(this, '.$id.')" /> Toggle All';
// change here onClick="toggle(this, $id)" to onClick="toggle(this, '.$id.')"
echo '</td>';
for ($y = 0; $y < 7; $y++){
echo "<td>";
echo '<input type="checkbox" name="'.$id.'" value="bar1"> Bar 1<br/>';
// also change the name=$id to name="'.$id.'"
echo '</td>';
}
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>
I am not sure about your javascript, but it for sure needs the change I made to it.
<!DOCTYPE html>
<html>
<head>
<script language="JavaScript">
// change to-> Id from-> $id
function toggle(source, Id) {
checkboxes = document.getElementsByName(Id);
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
</head>
<body>
<table>
<?php
for ($x = 0; $x < 3; $x++) {
$id = $x; ?>
<tr>
<td>
<!--$id won't work in single quotes like that so you have to break it out.
See comment below, but you may need to base the toggle on the class-->
<input type="checkbox" onClick="toggle(this, '<?php echo $id; ?>')" /> Toggle All
</td><?php
for ($y = 0; $y < 7; $y++){ ?>
<td>
<!-- You will likely need to array this name, because if the
names are all the same, it will only take one value -->
<input type="checkbox" name="<?php echo $id; ?>[]" class="sub-<?php echo $id; ?>" value="bar1"> Bar 1<br/>
</td><?php } ?>
</tr><?php
} ?>
</table>

How to get MySQL query to carry over with PHP Pagination?

I am trying to keep my pagination based on the query I am using, but my problem is, it only works on the first page of pagination, and after that the query reverts to the standard one without filters (page one shows my filter, but page two show all results). I am wondering if there is an effective method that will carry over my filtered query when I click my pages, I am just at a loss right now as to how to accomplish this. Here is my code currently:
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<style type="text/css">
#win-range, #gaa-range, #sv-range{
width: 160px;
font-size: 10px;
margin: 0 auto;
}
#win-range a, #gaa-range a, #sv-range a{
margin-top: 0px !important;
padding: 0 !important;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function(){
$("#win-range").slider({
range: true,
min: 1,
max: 1000,
values: [1, 1000],
slide: function(event, ui) {
// in order to pass the user selected values to your app, we will use jQuery to prepopulate certain hidden form elements, then grab those values from the $_POST
$("#minwins").val(ui.values[0]);
$("#maxwins").val(ui.values[1]);
$("#winamount").val(ui.values[0] + " - " + ui.values[1]);
}
});
$("#winamount").val($("#win-range").slider("values", 0) + " - " + $("#win-range").slider("values", 1));
});
$(function(){
$("#gaa-range").slider({
range: true,
min: 0,
max: 10,
values: [0, 10],
slide: function(event, ui) {
// in order to pass the user selected values to your app, we will use jQuery to prepopulate certain hidden form elements, then grab those values from the $_POST
$("#mingaa").val(ui.values[0]);
$("#maxgaa").val(ui.values[1]);
$("#gaaamount").val(ui.values[0] + " - " + ui.values[1]);
}
});
$("#gaaamount").val($("#gaa-range").slider("values", 0) + " - " + $("#gaa-range").slider("values", 1));
});
$(function(){
$("#sv-range").slider({
range: true,
min: 750,
max: 1000,
values: [750, 1000],
slide: function(event, ui) {
// in order to pass the user selected values to your app, we will use jQuery to prepopulate certain hidden form elements, then grab those values from the $_POST
$("#minsv").val(ui.values[0]);
$("#maxsv").val(ui.values[1]);
$("#svamount").val(ui.values[0] + " - " + ui.values[1]);
}
});
$("#svamount").val($("#sv-range").slider("values", 0) + " - " + $("#sv-range").slider("values", 1));
});
</script>
<?php
include("includes/header.php");
include("includes/mysqli_connect.php");
$minwins = $_POST['minwins'];
$maxwins = $_POST['maxwins'];
$mingaa = $_POST['mingaa'];
$maxgaa = $_POST['maxgaa'];
$minsv = $_POST['minsv'];
$maxsv = $_POST['maxsv'];
$querySelection = $_POST['q'];
// FILTERING YOUR DB
$sortstats = $_GET['sortstats'];
$sortstatslow = $_GET['sortstatslow'];
// pagination
$getcount = mysqli_query ($con,"SELECT COUNT(*) FROM Player");
$postnum = mysqli_result($getcount,0);// this needs a fix for MySQLi upgrade; see custom function below
$limit = 6; //how many blog posts per page you will see.
if($postnum > $limit){
$tagend = round($postnum % $limit,0);
$splits = round(($postnum - $tagend)/$limit,0);
if($tagend == 0){
$num_pages = $splits;
}else{
$num_pages = $splits + 1;
}
if(isset($_GET['pg'])){
$pg = $_GET['pg'];
}else{
$pg = 1;
}
$startpos = ($pg*$limit)-$limit;
$limstring = "LIMIT $startpos,$limit";
}else{
$limstring = "LIMIT 0,$limit";
}
// MySQLi upgrade: we need this for mysql_result() equivalent
function mysqli_result($res, $row, $field=0) {
$res->data_seek($row);
$datarow = $res->fetch_array();
return $datarow[$field];
}
?>
<div class="listingcontainer">
<div class="sidebar">
<h3>Sort By:</h3>
Most Wins
Best Goals Against
Best Save %
<hr/>
<h3>Custom Filter</h3>
<br/>
<div class="custom-filter">
<form name="filters" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="filters">
<label for="winamount">Win Range:</label>
<input type="text" id="winamount" />
<div style="clear:both;"></div>
<input type="hidden" id="minwins" name="minwins" value="0" />
<input type="hidden" id="maxwins" name="maxwins" value="1000" />
<div id="win-range"></div>
<br/>
<label for="gaaamount">GAA:</label>
<input type="text" id="gaaamount" /><br />
<div style="clear:both;"></div>
<input type="hidden" id="mingaa" name="mingaa" value="0" />
<input type="hidden" id="maxgaa" name="maxgaa" value="10" />
<div id="gaa-range"></div>
<br/>
<label for="svamount">SV %:</label>
<input type="text" id="svamount" /><br />
<div style="clear:both;"></div>
<input type="hidden" id="minsv" name="minsv" value="750" />
<input type="hidden" id="maxsv" name="maxsv" value="1000" />
<div id="sv-range"></div>
<input type="submit" name="submit" id="submit"/>
</form>
</div>
</div>
<div class="main-listings">
<h1>Current NHL Goaltenders</h1>
<?php
$result = mysqli_query($con, "SELECT * FROM Player ORDER BY PlayerID ASC $limstring");
if(isset($sortstats)) {
$result = mysqli_query($con,"SELECT * FROM Player ORDER BY $sortstats DESC $limstring ") or die (mysql_error());
}
if(isset($sortstatslow)) {
$result = mysqli_query($con,"SELECT * FROM Player ORDER BY $sortstatslow ASC $limstring ") or die (mysql_error());
}
if(isset($_POST['submit']))
{
$result = mysqli_query($con, "SELECT * FROM Player WHERE Wins BETWEEN '$minwins' AND '$maxwins' AND
GAA BETWEEN '$mingaa' AND '$maxgaa' AND SavePerc BETWEEN '$minsv' AND '$maxsv'
ORDER BY PlayerID ASC $limstring") or die (mysql_error());
}
while($row = mysqli_fetch_array($result)){
$name = $row['LastName'] . ", " . $row['FirstName'];
$wins = $row['Wins'];
$pid = $row['PlayerID'];
$image = $row['Picture'];
$gaa = $row['GAA'];
$sv = $row['SavePerc'];
echo "<div class=\"player-listing\">";
echo "<div class=\"image-holder\">";
echo "<span class=\"helper\"></span>";
echo "<img src=\"admin/thumbs/$image\" alt=\"$name\">";
echo "</div>";
echo "<div style=\"clear:both;\"></div>";
echo "$name";
echo "<table align=\"center\">";
echo "<tr>";
echo "<td style=\"border-bottom: 1px solid #212121;\">Wins</td>";
echo "<td style=\"border-bottom: 1px solid #212121;\">GAA</td>";
echo "<td style=\"border-bottom: 1px solid #212121;\">SV%</td>";
echo "</tr>";
echo "<tr>";
echo "<td>$wins</td>";
echo "<td>$gaa</td>";
echo "<td>.$sv</td>";
echo "</tr>";
echo "</table>";
echo "</div>";
}
// paging links:
echo "<div class=\"paging\">";
if($postnum > $limit){
echo "<span class=\"page-numbers\"><strong>Pages:</strong> </span>";
$n = $pg + 1;
$p = $pg - 1;
$thisroot = $_SERVER['PHP_SELF'];
if($pg > 1){
echo "<< prev ";
}
for($i=1; $i<=$num_pages; $i++){
if($i!= $pg){
echo "$i ";
}else{
echo "$i ";
}
}
if($pg < $num_pages){
// INSERT QUERY STRING VARIBLE TO CARRY OVER DB QUERY
echo "next >>";
}
echo " ";
}
// end paging
echo "</div>";
?>
</div>
<div style="clear:both;"></div>
Save you search filters in session and always check the session value is set for any search or not and pass that data into you query.until and unless nobody reset that search criteria and when your user reset that search criteria to null then put the value blank in the session for that session search variable.
You need to pass all filter conditions to the paginating link, for example
$filter = "minwins={$minwins}&maxwins={$maxwins}&mingaa={$mingaa}&minsv={$minsv}&maxsv={$maxsv}&q={$querySelection}";
if($pg > 1){
echo "<< prev ";
}
for($i=1; $i<=$num_pages; $i++){
if($i!= $pg){
echo "$i ";
}else{
echo "$i ";
}
}
if($pg < $num_pages){
// INSERT QUERY STRING VARIBLE TO CARRY OVER DB QUERY
echo "next >>";
}
In the code for getting filter conditions from $_POST you are using, change it to $_REQUEST because it should get from URL ($_GET).
Ex
$minwins = $_REQUEST['minwins'];
You could always use the below to create a list of URL keys (filters).
foreach($_GET as $key => $value){
$url_keys .= $key . "=" . $value . "&";
}
And then add that into your URL for next/prev page.
echo "next >>";
You will then be passing your filters through the URL and have access to them on the next page.

Categories