2012-06-12 45 views
1

是否可以僅使用一個插入查詢來簡化以下代碼?將多個插入查詢合併爲一個

if(isset($_POST['colore'])) { 
    $range = array_keys($_POST['colore']); 
    foreach ($range as $key) { 
    $colore = $_POST['colore'][$key]; 
    $s = $_POST['S'][$key]; 
    $m = $_POST['M'][$key]; 
    $l = $_POST['L'][$key]; 
    $xl = $_POST['XL'][$key]; 
    $xxl = $_POST['XXL'][$key]; 

    $sql = "INSERT INTO store_product_attributes (`prod_id`, `color`, `size`, `qty`) 
    VALUES ('$last_id', '$colore', 's', '$s')"; 
    $query = mysql_query($sql) or die(mysql_error()); 
    $sql = "INSERT INTO store_product_attributes (`prod_id`, `color`, `size`, `qty`) 
    VALUES ('$last_id', '$colore', 'm', '$m')"; 
    $query = mysql_query($sql) or die(mysql_error()); 
    $sql = "INSERT INTO store_product_attributes (`prod_id`, `color`, `size`, `qty`) 
    VALUES ('$last_id', '$colore', 'l', '$l')"; 
    $query = mysql_query($sql) or die(mysql_error()); 
    $sql = "INSERT INTO store_product_attributes (`prod_id`, `color`, `size`, `qty`) 
    VALUES ('$last_id', '$colore', 'xl', '$xl')"; 
    $query = mysql_query($sql) or die(mysql_error()); 
    $sql = "INSERT INTO store_product_attributes (`prod_id`, `color`, `size`, `qty`) 
    VALUES ('$last_id', '$colore', 'xxl', '$xxl')"; 
    $query = mysql_query($sql) or die(mysql_error()); 
} 

}

+1

您的代碼非常難以閱讀。順便說一下,你的代碼可能會打開盲SQL注入。確保你的變量不能包含錯誤的SQL代碼。 – rekire

+5

我想訂購尺寸爲M的顏色爲''的; DROP TABLE store_product_attributes --'。 –

+1

你是一個邪惡的傢伙Linus;) – rekire

回答

2

你可以試試:

INSERT INTO store_product_attributes (`prod_id`, `color`, `size`, `qty`) 
VALUES ('$last_id', '$colore', 's', '$s'), ('$last_id', '$colore', 'm', '$m'), 
('$last_id', '$colore', 'l', '$l'), ('$last_id', '$colore', 'xl', '$xl'), 
('$last_id', '$colore', 'xxl', '$xxl'); 

但你的代碼是危險的。 SQL注入很容易使用該代碼,您應該瞭解更多關於安全性的信息(在google上輸入:「owasp」或「sql injection」)

+0

謝謝,但我已經證明了代碼,它太長了,是的,我插入它之前保護代碼 –

0

如果我認爲正確的話,應該可以插入多值模式:

INSERT INTO table (field1, field2, ...) VALUES (...), (...) 
3

你可以把它改寫這樣的:

$colore = mysql_real_escape_string($_POST['colore'][$key]); 
$s = mysql_real_escape_string($_POST['S'][$key]); 
$m = mysql_real_escape_string($_POST['M'][$key]); 
$l = mysql_real_escape_string($_POST['L'][$key]); 
$xl = mysql_real_escape_string($_POST['XL'][$key]); 
$xxl = mysql_real_escape_string($_POST['XXL'][$key]); 

$sql = " 
    INSERT INTO store_product_attributes 
     (`prod_id`, `color`, `size`, `qty`) 
    VALUES ('$last_id', '$colore', 's', '$s'), 
     ('$last_id', '$colore', 'm', '$m'), 
     ('$last_id', '$colore', 'l', '$l'), 
     ('$last_id', '$colore', 'xl', '$xl'), 
     ('$last_id', '$colore', 'xxl', '$xxl')"; 
$query = mysql_query($sql) or die(mysql_error()); 

重要:

確保到mysql_real_escape_string()查詢中使用的所有值!

雖然你這樣做,但最好切換到MySQLiPDO,因爲不鼓勵使用mysql擴展。