简体   繁体   中英

PHP function to increment variable by 1 each time script is executed

Is it possible to increment a variable or array by 1 each time the script is executed.

An example would be, I execute the script and it sets a variable to $increment = '1';

I then close the script and come back 30 min later to execute the script again.

This time the variable needs to be $increment = '2';

The script will be run from cron every 30 minutes for a total of 8 times.

After the 8th execution the variable would need to be rewound back to $increment = '1';

Is this possible through session? Can session be setup for the cli sapi ?

Or would it be easier to output a text file with the next increment number and just pull the value from the text file?

All help is appreciated.

You will have to persist the value of the variable to a non-volatile source between calls to the script. Furthermore, you'll have to consider race conditions if (as is often the case) the script can be called at almost the same time.

The best bet for this, is to store your variable in a database that maintains transactional safety. Even most cheap webhosters offer some form of database that will meet this requirement ... the specifics depend on your particular setup.

Store the counter value in database and on execution of the script update counter with + 1

Example script

$conn = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

if($query = $conn->query("YOU ACTION QUERY HERE"))
{
    // Here you call your actions of script

    /* Increment the counter field here. */
    $conn->query("UPDATE table SET counter = counter + 1");
}

$conn->close();

Note Its simple logic to increment variable by 1 each time script is executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM