Rohit Tripathi
Rohit Tripathi

Reputation: 39

SESSION unable to Retain Values | Logical Error in PHP Code

AIM OF MY PROGRAM 1. 5-6 circles be shown on my site of blue color each. 2. Whenever, a circle is clicked it should turn RED or GREEN permanently.

Here is my Code:

<?php session_start(); ?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Let's see !</title>
</head>
<body>
<?php 
define("SIZE", 5);


for ( $i = 0 ; $i < SIZE ; $i++ ) //Initializes all Color Blocks to BLUE if not clicked
    {
        //If Image has been clicked, it takes a Color RED or GREEN
            if ( isset($_POST[$i."form"]) ) 
        {
            if($i % 2 == 0)
            $_SESSION[$i] = "green.jpg";
            else
            $_SESSION[$i] = "red.jpg";
        }
        else
        {   //to check if image was previously clicked.
            if ( $_SESSION[$i] == "green.jpg")
                $_SESSION[$i] = "green.jpg";

            elseif ( $_SESSION[$i] == "red.jpg")
                $_SESSION[$i] = "red.jpg";  
            else    //if never clicked it will be made blue.
                $_SESSION[$i] = "blue.jpg";  
        }
    }

for ( $i = 0 ; $i < SIZE ; $i++ )
{
?>
<form method="POST" action="index.php">
<input type="image" width=120 src="<?php echo $_SESSION[$i]; ?>" name="mainin"/> 
<input type="hidden" name="<?php echo $i."form"; ?>" value="" /> 
</form>
<?php }
echo session_id(); //Sessions are working correctly. No issue with them.
?>
</body>
</html>

What Happens in this program ? Whenever a circle, is clicked it turns to RED. When, the second circle is clicked, it turns to GREEN, and the first circle shows up as BLUE. Whereas, when the second circle is clicked, the first circle should show as red and second one as green.

As Far as i feel, there is a logical or conceptual error in this program. If somebody can tell me where i went wrong, i shall be greatful. I have been trying to figure this out for hours.

Upvotes: 0

Views: 82

Answers (2)

escitalopram
escitalopram

Reputation: 3864

Only one form gets submitted at a time. If you click on your first image, the code for the other images goes into the else branch ("to check if image was previously clicked") and the color is reset to blue. BTW: Only the "blue" line in said branch does anything at all, you can delete the rest. Also, you should check if the session field is empty before setting it to "blue".

Upvotes: 1

David
David

Reputation: 2065

$SESSION's cannot begin with a numerical key, append them with something like circle, e.g.:

$_SESSION['circle_'.$i]

Hope that helps. I tested it on my system and this fixes the issue.

Upvotes: 2

Related Questions