LoginSignup
0
0

More than 1 year has passed since last update.

PHPで1年分の月を出力する。

Last updated at Posted at 2021-09-09

PHPで一年分の月を出力する。

データベースに月毎でデータを保存しているってことはまあまああることだと思います。
一年単位で一括更新したいデータがあったのですが、テーブルが別れているのでめんどくさいのでfor文で一気に更新してしまいます。

for文といえば

for($i = 0; $i < 12; $i++){
  //なんか処理
}

こんな感じだと思うんですけど、今回は

$to_month = date("Ym");
//1年後
$limit_month = date("Ym", strtotime(date("Ymd")." +1 year"));

for($m = $to_month; $m <= $limit_month; $m = date("Ym", strtotime($m."01 +1 month"))){

    echo "<pre>";
    var_dump($m);
    echo "</pre>";
}

// string(6) "202109"
// string(6) "202110"
// string(6) "202111"
// string(6) "202112"
// string(6) "202201"
// string(6) "202202"
// string(6) "202203"
// string(6) "202204"
// string(6) "202205"
// string(6) "202206"
// string(6) "202207"
// string(6) "202208"
// string(6) "202209"

こんな感じ。

strtotimeは直感的でわかりやすいですよね!私はよく使ってます。

そしてデータベースを更新したいときはSQLを中に書いてあげて

$to_month = date("Ym");
//1年後
$limit_month = date("Ym", strtotime(date("Ymd")." +1 year"));

for($m = $to_month; $m <= $limit_month; $m = date("Ym", strtotime($m."01 +1 month"))){

    $table = "data_table_".$m;
    $sql = "UPDATE {$table} SET ******";

    echo "<pre>";
    var_dump($sql);
    echo "</pre>";
}

// string(42) "UPDATE data_table_202109 SET ******"
// string(42) "UPDATE data_table_202110 SET ******"
// string(42) "UPDATE data_table_202111 SET ******"
// string(42) "UPDATE data_table_202112 SET ******"
// string(42) "UPDATE data_table_202201 SET ******"
// string(42) "UPDATE data_table_202202 SET ******"
// string(42) "UPDATE data_table_202203 SET ******"
// string(42) "UPDATE data_table_202204 SET ******"
// string(42) "UPDATE data_table_202205 SET ******"
// string(42) "UPDATE data_table_202206 SET ******"
// string(42) "UPDATE data_table_202207 SET ******"
// string(42) "UPDATE data_table_202208 SET ******"
// string(42) "UPDATE data_table_202209 SET ******"

これで楽々更新♪

仮に10年とかになっても応用が効きそうですね。

0
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0