2013-07-25 50 views
0

我想插入動態月份到數據庫中,如果用戶選擇March,那麼我需要從3月到2月插入12個月的記錄。我獲得了動態的月份,但是當我試圖將其插入數據庫時​​,它只插入前12個月。如果用戶點擊添加更多按鈕,我需要在3月至2月再次重複循環。這是我的代碼:如何在循環中重複月份?

$months = array(); 
$date="august"; 
$year= '2014'; 
//$y= (int)$year; 
$currentMonth= date('m', strtotime($date)); 
$currentyear= date('Y', strtotime('+1 year')); 
for($x = $currentMonth; $x < $currentMonth+12; $x++) 
{ 
    $months[] = date('F Y', mktime(0, 0, $currentyear, $x,1)); 
} 
//print_r($months); 
for($i=0; $i<=23 ; $i++) 
{ 

echo $insert= "insert into month(month_name) values('".$months[$i]."')"; 

} 
+0

其實,聽起來好像你的數據庫模型很奇怪。爲什麼你要插入所有十二個月,以一定的順序? 此外,months數組的長度不會超過12,因此直到23的循環將導致錯誤。 – Hidde

回答

0

爲您的月陣列只有12個值,你不能去該數組中值23。你可以做的是通過陣列運行兩次從0到11,這樣的:

for($j=0; $j<2 ; $j++) 
{ 
    for($i=0; $i<12 ; $i++) 
    { 
    echo $insert= "insert into month(month_name) values('".$months[$i]."')"; 
    } 
} 

或克萊德表示可以使用模運算符,它不會讓你浪費了2個循環,從而更快:

for($i=0; $i<24 ; $i++) 
    { 
    echo $insert= "insert into month(month_name) values('".$months[$i % 12]."')"; 
    } 
+0

你浪費兩個循環的東西,可能是一個,使用模運算符 – CBIII

+0

我怎麼能找到$ j循環中的2的動態值。 – user1523311

+0

因爲您的演示並未顯示動態值,我似乎無法知道您的動態值應該來自哪裏。在你的演示中,你也只是在那裏硬編碼「23」。這個變量應該如何定義呢?這是你正在談論的「添加按鈕」嗎? –

0

也許你可以使用DateTime對象來做到這一點。

$string = '01-08-2013'; //input string from user 

$StartDate = new DateTime($string); 
$StopDate = new DateTime($string); 
$StopDate->modify('+1 year'); 

while($StartDate < $StopDate) { //loop as long as $StartDate is smaller than $StopDate 
    echo "inserting " . $StartDate->format('d/m/Y') . ' into database ' . "<br/>"; 

    //execute mysql query; 

    $StartDate->modify('+1 month'); 
} 
0

你的問題應該說明爲什麼你想在數據庫中的這一系列月份,因爲沒有人通常這樣做。通常情況下,人們會將交易記錄/事件記錄的時間戳放入數據庫中,然後報告。