将多个插入查询合并为一个

时间:2012-06-12 12:05:40

标签: mysql

是否可以仅使用一个插入查询来简化以下代码?

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());
}

}

3 个答案:

答案 0 :(得分:4)

您可以这样重写:

$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扩展名。

答案 1 :(得分: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”)

答案 2 :(得分:0)

如果我说得对,那么应该可以使用此模式插入多个值:

INSERT INTO table (field1, field2, ...) VALUES (...), (...)
相关问题