tags:

views:

44

answers:

4

Basically its a web page where someone would press a button to increment the $selection variable. Globals and statics do not seem to work. Code looks like this:

<?php

    if(isset($_POST['next'])) 
    {
        displaynext();
    }
    else
    {

        global $image_folder = "/images/";

        echo "global declared";

        global $selection;
        $selection = 1;
    } 

    function displaynext()
    { 
        $selection++;

        if (file_exists($image_folder."/".$selection.".png")) {

        echo "<img src=\"$image_folder/".$selection.".png\">";

    }
    else {

      echo "No next image was found for $selection in ".$image_folder."/".$selection.".png";

    }

    ?>


    <form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
    <input type="submit" name="next" value="Next">
    </form>
A: 

Just use another form element.

<input type=hidden name=selection value=1>

Do a sanity check like is_numeric on $_POST['selection'] before displaying the image tag. If $_POST['selection'] is set, increment it for the input tag above.

Full example:

<?php
$selection = 0;
$image_folder = "images/";
if (isset($_POST['selection'])) {
   $userSelection = $_POST['selection'];
   if (is_numeric($userSelection) && file_exists($image_folder . $userSelection)) $selection = $userSelection;
}

echo "<img src=\"images/" . $selection . ".png\">";

echo "<form action=\"" . $_SERVER['PHP_SELF'] . "\" method=post>";
echo "<input type=hidden name=selection value=\"" . ($selection + 1) . "\">";
echo "<input type=submit name=subnext value=\"Next\">";
Fosco
+3  A: 

Once PHP runs and the output is sent to the client, the code will not run unless the page is requested again from the server. You could create a session variable and use that to store the variable across page requests. You need to either access the page again or perform an AJAX request to call your PHP code again.

Scott M.
followed tutorial in your answer got it done - thanks!
tylercomp
A: 

Instead of using Global, why don't you use a $_SESSION var?

John Isaacks
A: 

Put:

global $selection

inside your function, so:

global $selection;
$selection++;
plor