Retain Information over successive Page Releaods in PHP - php

Here is the Aim of my Program.
I Want around 5-6 Circles to be shown on the page, of colors red and green.
When, any of the circle is clicked. Its color changes to BLUE.
Then, if i click any other circle on the page its color should also change to BLUE, and the circle previously clicked should also show as BLUE.
So, if i click all circles one by one, in succesive pageloads, all the circles should show up as blue.
And, when a blue circle is clicked, it should show its original color.
This loop should continue for-ever, until the page is closed.
This is what i have done till now.
define("SIZE", 5); //the no. of circles
class redblock
{
var $color;
function set_color($data)
{
$this->color = $data;
}
function get_color()
{
return $this->color;
}
function image_source()
{
$rval2 = $this->get_color();
echo $rval2;
}
function display_block()
{
$rval = $this->get_color();
echo "<img src = '",$rval,"' width=120> </br> " ;
}
}
for ($i=0 ; $i < SIZE ; $i++ ) //INIT color blocks
     { $rb[$i] = new redblock ; }
for ($i=0 ; $i < SIZE ; $i++ ) //color set
{
if(!isset($_POST[$i.'form']))
{
if ($i % 2 == 0) //even blocks are green
$rb[$i]->set_color("green.jpg");
else //odd blocks are red
$rb[$i]->set_color("red.jpg");
}
if ( $_POST[$i.'form'] == "blue.jpg" )
$rb[$i]->set_color("blue.jpg");
if(isset($_POST[$i.'form']))
$rb[$i]->set_color("blue.jpg");
} ?>
<?php
// BOTH BLOCKS when clicked repeatedly should turn to white and fro.
for ($i=0 ; $i < SIZE ; $i++ ) //display the blocks
{
echo "<form method ='post'>";
echo "<input type = 'image' width='120' src ='",$rb[$i]->image_source(),"'>";
echo "<input type='hidden' name='".$i,"form' value='",$rb[$i]-get_color(),"'>";
echo "</form>";
}
?>
What Happens, in this code.
1. Suppose, i click Circle 1. It turns to blue.
2. Then i click circle 2, it turns blue, but circle 1 becomes green again. I want circle one to retain the blue color.
Please give me the correct code, or guide me in the right direction. Even, a small help will be largely appreciated.
I have no knowledge of Javascript, etc. I only know PHP and HTML/CSS.
Thank you.

You can use either $_SESSION variables or set a cookie using setcookie() and then retrieving it with $_COOKIE on the successive page loads. Either way will get you temporary storage of the values. Sessions are the way to go if you want the values to disappear after the browser is closed. Cookies will persist until they expire or are cleared by the user.

You can use $_SESSION to store each of the circle's state and use it on successive page loads.

Related

PHP conditional processing required to display rotating banners continuously

I'm trying to do something a little different with a banner rotator.
Below is the script I am using to read two text files (stored on my root directory with .db extensions) to rotate banners on a website. One file holds a counter (FileDB), the other holds the HTML banner code (URLDB).
The URLDB file currently holds six lines of HTML code to display hyperlinked banners.
The following script builds an array and rotates these banners sequentially on the refresh of the page counting from 0 - 5, and it does this perfectly:
<?php
define('FILEDB', '/WORKING DIRECTORY/count.db');
define('URLDB', '/WORKING DIRECTORY/url.db');
function readURLS()
{
$fo = fopen(URLDB, 'r');
if( null == $fo )
return false;
$retval = array();
while (($line = fgets($fo)) !== false)
{
$retval[] = $line;
}
return $retval;
}
$list = readURLS();
if( false === $list )
{
echo "No URLs available";
}
else
{
$fo = fopen(FILEDB, 'a+');
$count = (fread($fo, filesize(FILEDB)) + 1) % count($list);
ftruncate($fo, 0);
fwrite($fo, "{$count}");
fclose($fo);
echo $list[$count];
}
?>
On the webpage that I want to display the banners there are eight placeholders. However I only have six banners.
Here is the PHP code in each of the placeholders:
Placeholder 1: <?php echo $list[$count];?>
Placeholder 2: <?php echo $list[$count +1];?>
Placeholder 3: <?php echo $list[$count +2];?>
Placeholder 4: <?php echo $list[$count +3];?>
Placeholder 5: <?php echo $list[$count +4];?>
Placeholder 6: <?php echo $list[$count +5];?>
Placeholder 7: <?php echo $list[$count +6];?>
Placeholder 8: <?php echo $list[$count +7];?>
With the count at 0 the 6 banners are displayed in placeholders 1 - 6 and placeholders 7 and 8 are blank.
With every refresh the counter is increase by one, showing each banner in the first placed holder and pulling the other banners through each placeholder from 5 through to 0, but leaving previously populated placeholders blank until the sixth banner is in placeholder one. Then on the next refresh banners 1 - 6 are once again shown.
This occurs because I've hardcoded the values in each placeholder and I am obviously attempting to reference an entry in the file that is out of the bounds of the array built by the above script.
You can see a working example here.
What I am trying to achieve is display all banners in the URLDB such that when the last entry is shown, the first entry is displayed in the next placeholder (which in this case is placeholder 7) and the 2nd entry is show in in placeholder 8.
The idea is that the banners move continuously through each of the placeholders like the carriages of a train with each page refresh and increment of the counter - one following the other.
So, now you have the background, on to my question.
Is there a way I can amend the script to store in a PHP variable the maximum number of entries in the URLDB file/array and subsequently add conditional processing in the placeholders to check when the counter reaches this maximum value, and reference the next valid value in the array (i.e. 0) such that the banners restart again in the surplus placeholders - so here are no blank or empty placeholders shown?
I imagine this might seem like a strange request. But of course I would appreciate any advice on how to achieve my goal based on where things are currently.
Once you use a loop things become a bit easier to manipulate.
Hopefully the following solves your problem.
$numOfBanners = count($list);
$numOfPlacements = 8;
for ($i=0; $i < $numOfPlacements; $i++) {
// use the modulus operator to come back around
$bannerID = $i % $numOfBanners;
echo $list[$bannerID];
}
More info on the modulus operator can be found here.

PHP Auto-highlight cell depending on data from database

I am working on a PHP application and stumbled upon a problem on auto-highlighting.. I want to ask how to auto-highlight a cell of a table, whose data came from a database, after checking if the value is negative, 0, or positive, Red for negative, yellow for 0 and green for positive.
Please note that I have no experience regarding JavaScript or Ajax and rudimentary knowledge only on CSS. Thank you.
If needed, I can post any part of my code here.
It might be helpful for you:
function getSampleStatus($sampleid){
if($sampleid==1){
$color="#007334";
}elseif($sampleid==2){
$color="#3f96e8";
}elseif($sampleid==3){
$color="#ff9900";
}elseif($sampleid==4){
$color="#ff9770";
}
else{
$color="#ff0000";
}
$query='Select status from config where status_id='.$sampleid;
$this->_db->setQuery( $query );
$status =$this->_db->loadResult();
return "<span style='color:".$color.";padding-left:200px;'>".$status."</span>";
}
This function simply adds different colors depending on sample status.
For example:
For disapproved records, color red.
For Approved records, color green.
For Lab completed records, color yellow and so on..
Edit:
For Simplicity, try this:
$yourdatafromdatabase = 3; //which is either -ve, zero or positive
if($yourdatafromdatabase < 0){
$color="#FF0000"; //red for less than zero
}elseif($yourdatafromdatabase== 0){
$color="#FFFF00"; //yellow for zero
}
else{
$color="#00FF00"; //green for positive
}
echo "<span style=\"color: $color\"> <h1> Wow Color! </h1></span>";
?>
Working Demo:>>
just write css in table tag e.g
if ($value <0)
{echo "<td bgcolor=\"#FF0000\">$value</td>";}

checkbox's stay checked after pagination in php

Hello i want any checkbox i am gonna check, to stay checked after pagination.
here is the code:
foreach($test as $string){
$queryForArray = "SELECT p_fname,p_id FROM personnel WHERE p_id = " .$string["p_id"]. " ;" ;
$resultForArray = mysql_query($queryForArray, $con);
$rowfForArray = mysql_fetch_array($resultForArray);
?>
<td id="<?php echo $rowfForArray["p_id"]?>" onclick="setStyles(this.id)" ><?php echo $rowfForArray["p_fname"]?></td>
<td><input id="<?php echo $rowfForArray["p_id"]?>" class="remember_cb" type="checkbox" name="how_hear[]" value="<?php echo $rowfForArray["p_fname"]?>"
<?php foreach($_POST['how_hear'] as $_SESSION){echo (( $rowfForArray["p_fname"] == $_SESSION) ? ('checked="checked"') : ('')); } ?>/></td>
</tr>
<tr>
I am geting the data from a search result i have in the same page , and then i have each result with a checkbox , so that i can check the "persons" i need for $_Session use.
The only think i want is the checkbox's to stay checked after pagination and before i submit the form!(if needed i can post the pagination code, but he is 100% correct)
In the checkbox tag use the ternary operation, without that foreach inside him:
<input [...] value="<?php echo $rowfForArray["p_fname"]?>" <?php $rowfForArray["valueToCompareIfTrue"] ? "checked='checked'" : ''; ?> />
because the input already is inside of 'for' loop, then each time of the loop will create a new checkbox wich will verify if need to being check or not.
I hope I have helped you.
A few ways to tackle this:
(Straight up PHP): Each page needs to be a seperate form then, and your "next" button/link needs to submit the form everytime they click next. The submit data should then get pushed to your $_SESSION var. The data can then be extracted and used to repopulate the form if they navigate backwards as well. Just takes some clever usage of setting the URL with the proper $_GET variables for the form.
(HTML5): This will rely more on JavaScript, but basically you get rid of pagination and then just break the entire data set into div chunks which you can hide/reveal with JavaScript+CSS or use a library like JQuery.
(AJAX): Add event listeners to the checkboxes so that when a button is checked an asynchronous call is made back to a PHP script and the $_SESSION variable is updated accordingly. Again, this one depends on how comfortable you are with JavaScript.
Just keep in mind that PHP = ServerSide & JavaScript = ClientSide. While you can hack some PHP together to handle "clientside" stuff, its usually ugly and convoluted...
I did it without touching the database...
The checkbox fields are a php collection "cbgroup[]".
I then made a hidden text box with all the values which equal the primary keys of the selectable items mirroring the checkboxes. This way, I can iterate through the fake checkboxes on the current page and uncheck the checkboxes by ID that exist on the current page only. If the user does a search of items and the table changes, the selectable items remain! (until they destroy the session)
I POST the pagination instead of GET.
After the user selects their items, the page is POSTED and I read in the hidden text field for all the checkbox IDs that exist on that current page. Because PhP only tells you which ones are checked from the actual checkboxes, I clear only the ones from the session array that exist on the POSTED page from this text box value. So, if the user selected items ID 2, 4, 5 previously, but the current page has IDs 7,19, and 22, only 7, 19, and 22 are cleared from the SESSION array.
I then repopulate the array with any previously checked items 7, 19, or 22 (if checked) and append it to the SESSION array along with 2, 4, and 5 (if checked)
After they page through all the items and made their final selection, I then post their final selections to the database. This way, they can venture off to other pages, perhaps even adding an item to the dB, return to the item selection page and all their selections are still intact! Without writing to the database in some temp table every page iteration!
First, go through all the checkboxes and clear the array of these values
This will only clear the checkboxes from the current page, not any previously checked items from any other page.
if (array_key_exists('currentids', $_POST)) {
$currentids = $_POST['currentids'];
if (isset($_SESSION['materials']) ) {
if ($_SESSION['materials'] != "") {
$text = $_SESSION['materials'];
$delimiter=',';
$itemList = explode($delimiter, $text);
$removeItems = explode($delimiter, $currentids);
foreach ($removeItems as $key => $del_val) {
//echo "<br>del_val: ".$del_val." - key: ".$key."<br>";
// Rip through all possibilities of Item IDs from the current page
if(($key = array_search($del_val, $itemList)) !== false) {
unset($itemList[$key]);
//echo "<br>removed ".$del_val;
}
// If you know you only have one line to remove, you can decomment the next line, to stop looping
//break;
}
// Leaves the previous paged screen's selections intact
$newSessionItems = implode(",", $itemList);
$_SESSION['materials'] = $newSessionItems;
}
}
}
Now that we have the previous screens' checked values and have cleared the current checkboxes from the SESSION array, let's now write in what the user selected, because they could have UNselected something, or all.
Check which checkboxes were checked
if (array_key_exists('cbgroup', $_POST)) {
if(sizeof($_POST['cbgroup'])) {
$materials = $_POST['cbgroup'];
$N = count($materials);
for($i=0; $i < $N; $i++)
{
$sessionval = ",".$materials[$i];
$_SESSION['materials'] = $_SESSION['materials'].$sessionval;
}
} //end size of
} // key exists
Now we have all the items that could possibly be checked, but there may be duplicates because the user may have paged back and forth
This reads the entire collection of IDs and removes duplicates, if there are any.
if (isset($_SESSION['materials']) ) {
if ($_SESSION['materials'] != "") {
$text = $_SESSION['materials'];
$delimiter=',';
$itemList = explode($delimiter, $text);
$filtered = array();
foreach ($itemList as $key => $value){
if(in_array($value, $filtered)){
continue;
}
array_push($filtered, $value);
}
$uniqueitemschecked = count($filtered);
$_SESSION['materials'] = null;
for($i=0; $i < $uniqueitemschecked; $i++) {
$_SESSION['materials'] = $_SESSION['materials'].",".$filtered[$i];
}
}
}
$_SESSION['materials'] is a collection of all the checkboxes that the user selected (on every paged screen) and contains the primary_key values from the database table. Now all you need to do is rip through the SESSION collection and read\write to the materials table (or whatever) and select/update by primary_key
Typical form...
<form name="materials_form" method="post" action="thispage.php">
Need this somewhere: tracks the current page, and so when you post, it goes to the right page back or forth
<input id="_page" name="page" value="<?php echo $page ?> ">
if ($page < $counter - 1)
$pagination.= " next »";
else
$pagination.= "<span class=\"disabled\"> next »</span>";
$pagination.= "</div>\n";
Read from your database and populate your table
When you build the form, use something like this to apply the "checked" value of it equals one in the SESSION array
echo "<input type='checkbox' name='cbgroup[]' value='$row[0]'";
if (isset($filtered)) {
$uniqueitemschecked = count($filtered);
for($i=0; $i < $uniqueitemschecked; $i++) {
if ($row[0] == $filtered[$i]) {
echo " checked ";
}
}
}
While you're building the HTML table in the WHILE loop... use this. It will append all the select IDs to a comma separated text value after the loop
...
$allcheckboxids = "";
while ($row = $result->fetch_row()) {
$allcheckboxids = $allcheckboxids.$row[0].",";
...
}
After the loop, write out the hidden text field
echo "<input type='hidden' name='currentids' value='$allcheckboxids'>";

Custom PHP Pagination

I use the code below to do a "next" and "previous" navigation. It works but even when there is 1 entry the next button shows and when there are more than 20 entries and once they have been served the code shows next and previous. How can I make it so that the next button will only show if there are more than 10 and how do I show no next and previous button if there are no more results to show:
if (!isset($_GET['pg']) or !is_numeric($_GET['pg'])) {
$startrow = 0;
} else {
$startrow = (int)mysql_real_escape_string($_GET['pg']);
}
echo '<a id=pgnvg href=
"'.$_SERVER['PHP_SELF'].'?pg='.($startrow+20).'& q='.($what).'">Next</a>';
$prev = $startrow - 20;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0)
echo '<a id=pgnvg2 href="'.$_SERVER['PHP_SELF'].'?pg='.$prev.'">Previous</a>';
you need to add a check on how many items are actually returned e.g:
if($itemAmount > 20) {
echo '<a id=pgnvg href=
"'.$_SERVER['PHP_SELF'].'?pg='.($startrow+20).'& q='.($what).'">Next</a>';
}
otherwise the next button will always display
Assume that you have a variable $itemsCount containing the number of items into the recordset.
If you don't have one you can calculate it with a query like
count(*) FROM <wathever table or join> WHERE <list of conditions>
Further I would use a constant called ITEMS_ON_A_PAGE (Hope you will guess its content ;)
define ('ITEMS_ON_A_PAGE',20); // put it where more appropriate
...
if (!isset($_GET['pg']) or !is_numeric($_GET['pg'])) {
$startrow = 0;
} else {
// no need to issue a mysql query, you need an integer from a numeric variable
$startrow = (int)$_GET['pg'];
}
$linkTemplate = '<a id="%s" href="?%s">%s</a>';
$nextPageFirstItem = $startrow + ITEMS_ON_A_PAGE;
$previousPageFirstItem = $startrow - ITEMS_ON_A_PAGE;
if ($itemsCount> $nextPageFirstItem) {
echo printf($linkTemplate,
'pgnvg',
http_build_query(array('pg'=>$nextPageFirstItem,'q'=>$what)),
'Next'
);
}
if ($previousPageFirstItem >= 0) {
echo printf($linkTemplate,
'pgnvg2',
http_build_query(array('pg'=>$previousPageFirstItem,'q'=>$what)),
'Previous'
);
}
Here there is the reference for the http_build_query that creates the query for you
There will be a lot of room to improve this code but, as a starting point, it would suffice ;)
You might actually want to use a switch statement. Sometimes if statements stop working when you have too many of them and too many evaluate to be true. Just pay attention to when you want to break; vs not breaking (don't include break;).

Loop Iteration in Php Game

Trying to get it to loop through 3 times and after the 3rd time (if not guessed right) show the right answer.
Currently - its going through the guesses, but isnt showing how many guesses are left (should be deducting each # each attempt).
Anyone? If you could show me where I'm going wrong here.
<style type="text/css">
input {border:1px solid #ADD8E6; font-size:1.2em;}
input.spec {background-color:#ddd;}
</style>
<?php
echo "<fieldset><h1><legend>Testing your Academy Award Trivia</h1>";
$ages['Casablanca'] = "1943";
$ages['Around The World in 80 Days'] = "1956";
$ages['Patton'] = "1970";
$ages['Annie Hall'] = "1977";
$ages['Chariots of Fire'] = "1981";
$ages['Dances With Wolves'] = "1990";
$ages['Crash'] = "2005";
$ages['The Departed'] = "2006";
$rand_keys = array_rand($ages, 1);
$guesses = 3;
?>
<form method='post' name="inputyear" onsubmit="return validate(this);">
Give the year below won academy award<br><br>
<Strong>Movie:</strong> <input type='text' name='movie' class="spec" value='<?= $rand_keys ?>' readonly='readonly' /><br><br>
<Strong>Year it Won the Oscar:</Strong> <input type='text' name='year' size="30" /><br/><br>
<strong>You have: </strong> <?php $guesses; ?> guesses left<br><br>
<input type='submit' name='submit' value="Get Result" onClick="makeGuess()" />
</form>
<?php
$movie = isset($_POST['movie']) ? $_POST['movie'] : false;
$guessedYear = isset($_POST['year']) ? (int) $_POST['year'] : false;
if ($movie && $guessedYear) {
$realyear = $ages[$movie];
}
#$_SESSION[$movie]['$guesses']++;
if ($realyear && $_SESSION[$movie]['$guesses'] < 3) {
if ($guessedYear == $realyear) {
echo "Correct! " . "during year " . $realyear;
}
if ($guessedYear < $realyear) {
echo "Wrong, year too low";
$guesses--;
}
if ($guessedYear > $realyear) {
echo "Wrong, year too high";
$guesses--;
}
} elseif ($_SESSION[$movie]['$guesses'] >= 3) {
echo "Sorry, too many tries. the answer was " . $realyear;
} else {
echo "Sorry, You managed not to pick a year. Please try again";
$_SESSION[$movie]['guesscount']--;
}
?>
the return statement is leaving the loop and the script
get rid of both return statements
DC
Further to your comments on the duplicate question at...
Allowing 3 attempts at game - php
It would appear that this question is a 'homework' question as such and in fact with all questions no-one will give you the complete answer, nor in my opinion should they. We all expect that the person asking the question will take it upon themselves to investigate and understand the answers given.
Now in the case of your question, you appear to be missing a vital piece of information about how HTTP works (http is the protocol that drives all web pages and many other parts of the internet).
http is what's considered a stateless protocol, that is when you click on a link in a web page and go to another web page (or even the same web page), the new web page considers you a totally new visitor. It in effect has forgotten you.
Because this introduced issues for things like shopping carts (and PHP games) cookies were invented. this allowed the browser to carry around a small bit of information about you, in this way the web server or application remembered you. This has been extended into what respondents here are calling sessions.
A session is (usually) a cookie that stores an identifier. that identifier tells, in this case PHP, that you have been there before and where to find the information about you. PHP can load this information and make it available to you the programmer.
This happens EVERY TIME a page is loaded.
Now PHP does not know what to store in this 'session' it is up to you the programmer to decide what information needs to be stored. you need to tell PHP to save this information for the next time the page is loaded.
In your case its up to you to decide what needs to be remembered. Consider the reloading of the page to be a new 'iteration' of the loop. this should lead you to some obvious conclusions about what needs to be passed from one iteration to the next.
There you go. I haven't written the answer for you but hopefully have provided enough for you to pass your class in flying colours.
DC
I think you're problem is this line $rand_keys = array_rand($ages, 1);. Each time the user submits their answer a new $rand_keys is selected and fed into the dropdown regardless of what the submitted answer was.
So you'll want to check if there exists an answer (otherwise it's the first time the page is loaded). If there is an answer and it was correct then show a congrats message and generate a new movie id.
if($_POST['submit']) {
$movie = $_POST['movie'];
$guessedYear = $_POST['year'];
if ($guessedYear == $ages[$movie]) {
// well done you got it right, next movie
$rand_keys = array_rand($ages, 1);
}
else if ($guessedYear == $ages[$movie] && $_POST['tries'] >= 3) {
// took over 3 tries and didn't get it right, next movie
$rand_keys = array_rand($ages, 1);
}
else {
// find $movie index from $ages and use that
}
// you have one less try
$tries = $_POST['tries'] - 1;
}
else {
$rand_keys = array_rand($ages, 1);
$tries = 3;
}
Then in the form send the $tries variable along with the other ones, or as the other people here have said put it in the session variables. With that I think you should be able to remove the while loop completely.
After you fix what DeveloperChris says, you still need to put guesscount into as session or form field, and increment on each attempt.
if($guesscount < 3 && $guessedYear > $realyear){
echo "Wrong, year too high";
}
if($guesscount < 3 && $guessedYear > $realyear){
echo "Wrong, year too high";
}
duplicate code there. also i think you are looking for if{...}else if{..}else if{...}else{...}
and your question has nothing to do with javascript.
maybe core logic more like this?
$movie = isset($_POST['movie']) ? $_POST['movie'] : false;
$guessedYear = isset($_POST['year']) ? (int) $_POST['year'] : false;
if ($movie && $guessedYear) {
$realyear = $ages[$movie];
}
#$_SESSION[$movie]['guesscount']++;
if ($realyear && $_SESSION[$movie]['guesscount'] < 3) {
if ($guessedYear == $realyear) {
echo "Correct! " . "during year " . $realyear;
}
if ($guessedYear < $realyear) {
echo "Wrong, year too low";
}
if ($guessedYear > $realyear) {
echo "Wrong, year too high";
}
} elseif ($_SESSION[$movie]['guesscount'] >= 3) {
echo "Sorry, too many tries. the answer was " . $realyear;
} else {
echo "Sorry, You managed not to pick a year. Please try again";
$_SESSION[$movie]['guesscount']--;
}

Categories