简体   繁体   English

每次执行脚本时,PHP函数会将变量加1

[英]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. 每次执行脚本时,是否可以将变量或数组加1。

An example would be, I execute the script and it sets a variable to $increment = '1'; 一个例子是,我执行脚本并将其变量设置为$increment = '1';

I then close the script and come back 30 min later to execute the script again. 然后关闭脚本,并在30分钟后返回以再次执行脚本。

This time the variable needs to be $increment = '2'; 这次变量需要为$increment = '2';

The script will be run from cron every 30 minutes for a total of 8 times. 该脚本每30分钟从cron运行一次,共8次。

After the 8th execution the variable would need to be rewound back to $increment = '1'; 在第8次执行后,该变量将需要退回到$increment = '1';

Is this possible through session? 这可以通过会话吗? Can session be setup for the cli sapi ? 可以为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 将计数器值存储在数据库中,并在执行脚本更新计数器时加+ 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. 注意每次执行脚本时,将变量加1的简单逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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