Jump to content
Larry Ullman's Book Forums

How to loop or iterate variable in every click of button?


Recommended Posts

 I am new at php. I am trying to loop a number in each click of a button. See attached picture for reference.

1 should iterate after the click of the button and will stop to iterate when it gets to 5. 

 

Here is my code:

<!DOCTYPE html>
<html>
<body>

<div>Question <?php 
    $num = 5;
    $n = 1;
    $n <= $num;
    echo $n;
    
    
?> of <?php echo $num;?></div>

    <form method="post">
    <button id="button" class="button" value="add" name="add">Click</button>
    </form>
 

</body>
</html>

 

If I try to loop it this way,

<!DOCTYPE html>
<html>
<body>

<div>Question <?php 
    $num = 5;
    for($i = 1; $i <= $num; $i++){
    	echo $i;
    }
    
?> of <?php echo $num;?></div>

    <form method="post">
    <button id="button" class="button" value="add" name="add">Click</button>
    </form>
 

</body>
</html>

the result is Question 12345 of 5.

Capture.PNG

Link to comment
Share on other sites

Hey! You're having this problem because PHP runs on the server, which means all of your PHP code has already been executed before you see the HTML page in the browser. 

Secondarily, your button as written doesn't actually do anything. There's no programming logic attached to it. That would require JavaScript, which runs in the client. 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...