2012-06-18 82 views
0

我有一個允許用戶註冊多個事件的表單。它們以複選框的形式列出(所有命名爲registrations[],事件ID均爲值),並以數組形式提交。從foreach循環建立數組

那麼,隨後的頁面通過每個「檢查」事件循環,增加一條記錄到數據庫中的每個事件:

foreach ($_POST['registrations'] as $registration) { 

$query="SELECT exhibitions.exhib_id, DATE_FORMAT(exhibitions.exhib_date, %d/%m/%y'), venues.venue_name FROM exhibitions, venues WHERE  exhibitions.venue_id='$registration' AND venues.venue_id='$registration' LIMIT 1"; 
$result=mysql_query($query); 
$vr=mysql_fetch_array($result, MYSQL_NUM); 
$exhib_id=$vr[0]; 
$exhib_date=$vr[1]; 
$exhib_venue=$vr[2]; 

// do database stuff here 

} 

我需要做的是每個$exhib_date$exhib_venue存儲在單獨的數組,稍後我可以重複使用(在確認電子郵件中,其中將列出用戶已註冊的所有事件)。

我認爲這將會很簡單,建立一個新的陣列以外的foreach循環例如, $events_attending=array();並向內的數組添加元素,foreach循環例如$events_attending['date'] = $exhib_date;$events_attending['venue'] = $exhib_venue;

我測試了這個減去使用print_r()的foreach循環,它工作正常 - 所以我猜這就是我的問題所在?

任何人都可以幫忙嗎?提前致謝!

+0

請務必清理您的$ _POST! – Drewdin

回答

0

除了消毒你的$ _ POST數據,嘗試:

foreach ($_POST['registrations'] as $registration) { 

    $query="SELECT exhibitions.exhib_id, DATE_FORMAT(exhibitions.exhib_date, %d/%m/%y'), venues.venue_name FROM exhibitions, venues WHERE  exhibitions.venue_id='$registration' AND venues.venue_id='$registration' LIMIT 1"; 
    $result=mysql_query($query); 
    $vr=mysql_fetch_array($result, MYSQL_NUM); 
    $event[$exhib_id] = array('date' => $vr[1], 'venue' => $vr[2]); 

// do database stuff here 

} 

然後,你可以做:

print_r($event); 

Array(
    [1] => Array (
      date => 'event date', 
      venue => 'venue' 
      ) 
    [2] => Array (
      date => 'event date', 
      venue => 'venue' 
      ) 

如果你知道你想要什麼時,你可以調用:

$event[2]['date'] to get event date, or $event[2]['venue'] for the venue, etc. 
0
$events_attending[] = array('date' => $exhib_date, 'venue' => $exhib_venue); 

這附加你的值t數組的末尾,而不是每次循環迭代覆蓋它們。

+0

Hi MrSlayer。謝謝你的幫助。但是當我做一個'print_r($ events_attending)'時,我得到的只是:1.任何想法? – Martin

+0

沒有看到您的代碼,很難確定您做錯了什麼。在循環之前定義'$ events_attending = array();'。最後在循環內添加上面的行。然後在循環關閉後執行'print_r($ events_attending);'。 – Quantastical

+0

嗯,這就是我得到的。我實際上是直接在電子郵件中測試輸出,這些輸出將在用戶預訂活動後發送給用戶。我正在使用PHPMailer,但這不應該有任何區別,應該嗎? – Martin

0

我認爲最簡單的方法是將這些線條更改

$exhib_date=$vr[1]; 
$exhib_venue=$vr[2]; 

$exhib_date[]=$vr[1]; 
$exhib_venue[]=$vr[2]; 

,然後你將有兩個數組用於後來被命名爲

$exhib_date 
$exhib_venue 
0

你是正確的在你的猜測中,你只是錯過了一個小的(但很大的)細節。您需要將該數組的每一行與某種類型的另一個標識符區分開來。例如:

$events_attending[$exhib_id]['date'] = $exhib_date; 
$events_attending[$exhib_id]['venue'] = $exhib_venue; 

乾杯。

0

它看起來像你正在覆蓋你陣列中的相同條目。試試這個:在我看來

$events_attending[] = array('date' => $exhib_date, 'venue' => $exhib_venue); 

順便說一句,你真的應該到位mysql_fetch_array()的使用mysql_fetch_assoc(),它確實有助於避免錯誤,當你維護你的代碼。

哦,是的,一定要使用mysql_real_escape_string()在您的查詢中注入的POST值,人們可以執行SQL注入!

+0

感謝Simon(和其他所有人提供了類似的建議!)看起來應該可以工作,但是如果我做一個'print_r($ events_attending)',我得到的唯一結果是:1.任何想法?! – Martin

+0

嗯,我想你必須發佈你的代碼再次。 – Simon