Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
只执行一次的PHP代码_Php - Fatal编程技术网

只执行一次的PHP代码

只执行一次的PHP代码,php,Php,我有一个php代码,我只想执行一次,也就是说,它应该在第一次安装时加载,第二次不应该执行。我尝试了for和if条件,但对我无效 这是我的代码: $table = self::checkTablesExist(); if(empty($table)) { self::createTables(); self::createRootUser(self::$preflight_config); if(self::$preflight_config->

我有一个php代码,我只想执行一次,也就是说,它应该在第一次安装时加载,第二次不应该执行。我尝试了
for
if
条件,但对我无效

这是我的代码:

$table = self::checkTablesExist();

    if(empty($table)) { 
    self::createTables();

    self::createRootUser(self::$preflight_config);
        if(self::$preflight_config->sample_data == 1) { 
            self::installSampleData();
        }
    }

您可以尝试创建一个类似于数据库锁的系统

因此,第一次运行代码时,您创建一个文件
run.lock
,为空,这无关紧要,然后在每次执行时检查该文件是否存在,如果存在,则代码已运行,否则您应运行代码

注意在永久位置创建文件,而不是像
/tmp


或者更好,如果数据库中存在这些表,就不要运行代码。

这一切都取决于您要做什么,我从您的问题中可以看出,您正在尝试安装mysql数据表。。。这是正确的,您应该检查表是否存在

<?php
if (mysql_num_rows("show tables like `tablename`")!==1) {

  // Install table

}
?>

如果您希望基于完全不同的内容只运行一次代码,即不依赖数据库,则最好使用平面归档:

<?php
if (file_exists("should-we-run.cfg") && file_get_contents("should-we-run.cfg")=="Y") {

  // Execute code
  file_put_contents("should-we-run.cfg","No");
  // OR
  unlink("should-we-run.cfg");

}
?>


您能解释一下“首次安装时应该加载”是什么意思吗?什么不起作用?CheckTableExist()做什么?它是否检测到已经存在的表?数据填充到数据库中,checkTableExist方法检查特定数据库中是否存在表,以及您计划如何在执行任何其他代码之前运行.cfg?创建创建此文件的脚本不仅需要开销,而且可以重新运行该脚本以重新创建该文件,这样就可以重新运行其有问题的代码。因此,如果文件不存在,请翻转规则->执行代码并创建文件(空),然后只使用文件_exists();除非我们讨论的是巨大的性能需求,否则我看不到开销问题。。。然后使用数据库配置表来确定布尔索引,这样您就可以提供一个带有安装的run.lock文件,一旦创建了表,就可以删除该文件。仅当存在此文件时才执行表创建代码。例如,如果(文件_存在(“run.lock”){createtables}