2012-11-30 16 views
-2

我已經表命名爲subject。我不得不列id(PK),subject_nametotal_classattendencecnic(FK)。我的用戶填寫表格並提交。我通過表單的post方法獲得了值。在形式上,我有6個科目,併爲每個科目我有total_class,attendence,subject_name。 這裏是我的代碼我怎麼可以插入6倍值到MySQL表在單個查詢

if($_SERVER['REQUEST_METHOD']=='POST') 
{ 

    $form=$_POST[form']; 
    $s1=$_POST['sub1']; 
    $s1=$_POST['sub2']; 
    $s1=$_POST['sub3']; 
    $s1=$_POST['sub4']; 
    $s1=$_POST['sub5']; 
    $s1=$_POST['sub6']; 
    $month=$_POST['month']; 

    $total_attend_1=$_POST['Ts1']; 
    $total_attend_2=$_POST['Ts2']; 
    $total_attend_3=$_POST['Ts3']; 
    $total_attend_4=$_POST['Ts4']; 
    $total_attend_5=$_POST['Ts5']; 
    $total_attend_6=$_POST['Ts6']; 

    $attend_1=$_POST['Attend_s1']; 
    $attend_2=$_POST['Attend_s2']; 
    $attend_3=$_POST['Attend_s3']; 
    $attend_4=$_POST['Attend_s4']; 
    $attend_5=$_POST['Attend_s5']; 
    $attend_6=$_POST['Attend_s6']; 
    $query=mysql_query("INSERT INTO subject VALUE('','$s1','total_attend_1','$attend_1','$form','$month')") or die(mysql_error()); 
    /*My query should be here.Should I write 6 insert queries?*/ 

我曾用

foreach($array as $attendee){ 
} 

嘗試過,但沒有得到我的任務是什麼? 有人可以幫我嗎?

+4

首先,那麼您需要了解[sql注入漏洞](http://bobby-tables.com),那麼您需要了解[數據庫規範化](http://en.wikipedia.org/wiki/Database_normalization) –

+1

如果你有一個變量名在裏面有一個數字*,你應該使用一個數組* –

+0

@sam:沒有錯誤的數字在他們的變量。但其中肯定有順序/重複數字的變量。 –

回答

2

我想你想是這樣的:

function x($str) {return mysql_real_escape_string($str);} // shorter function name 
$rows = Array(); 
for($i=1; $i<=6; $i++) { 
    $rows[] = "(null,'".x($_POST['sub'.$i])."','".x($_POST['Ts'.$i])."','".x($_POST['Attend_s'.$i])."','".x($form)."','".x($_POST['month'])."')"; 
} 
mysql_query("insert into `subject` values ".implode(",",$rows)); 

刪除所有變量賦值,並確保您定義$form的地方 - 我沒有看到它在你發佈的代碼。

+0

我認爲Olaf Dietsche的答案對於新手而言更具人性化,更易於理解。 – Kamil

+0

@Kolink這個功能和我想要的完全一樣。非常感謝 –

3

正確insert語法

insert into subject values (sub1, ts1, attend_s1); 

或者您需要了解[陣列(http://php.net/array)多個值

insert into subject values (sub1, ts1, attend_s1), (sub2, ts2, attend_s2), (...); 
1
// $post = a sanitized copy of $_POST 

$entries = array(); 
for ($i = 1; $i <= 6; ++$i) { 
    $entries[] = " (NULL, '{$post['sub'.$i]}', '{$post['Ts'.$i]}', '{$post['Attend_s'.$i]}', '{$form}', '{$post['month']}') "; 
} 

$query = " INSERT INTO `subject` VALUES ".implode(', ', $entries); 
相關問題