Jump to content

global variable counter


jwrightnisha

Recommended Posts

Hello, I am  trying to increment a php variable by clicking on a button.

I've tried placing the variable in various spots and experimented with global and static keywords but I just can't get the variable to increment.

Any help would be greatly appreciated. Cheers, James

 

<html>

<head>

<title>Increment</title>

<?php static $i = 0; ?>

</head>

<body>

<?php

function incrementI()

{

$i++;

return $i++;

}

?>

<SCRIPT language="JavaScript">

<!--

function f1()

{

var val = "<?php echo incrementI(); ?>";

var message = "The value of i now is " + val;

alert(message)

}

//-->

</SCRIPT>

<input name="btnNext" type="button" id="btnNext" onClick="f1(); " value="Next">

</body>

</html>

Link to comment
https://forums.phpfreaks.com/topic/83542-global-variable-counter/
Share on other sites

A web page in a browser cannot directly "call" php code on the server. A browser can only make http/https requests to the web server.

 

Your button/link would either need to request the URL of a page that contains php code to increment the value or you can use AJAX to make the http request to the page.

 

You will also need to store the variable that is being incremented in a session (or a database) because all the resources that a .php page uses are destroyed when the code on that page reaches the end of the page. Static variables in functions are only static for the page they are on. They don't persist between page visits or page refreshes.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.