根据提供的数量将多个相同的行插入mysql DB

时间:2016-01-12 16:41:33

标签: php mysql insert

我希望根据网络表单中的数量向MySQL DB提供N个相同的行 目前,插入脚本一次只添加一行(" 1"是此数量输入的默认值)

这是这个脚本:

<?php 
require 'connect.php';

// define variables and set to empty values
$cosmInOut_name = $cosmInOut_dateIn = $cosmInOut_expire = $cosmInOut_priceIn = $cosmInOut_4sale = $cosmInOut_dateOut = $cosmInOut_qtyOut = $cosmInOut_priceOut = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $cosmInOut_name = test_input($_POST["cosmInOut_name"]);
  $cosmInOut_dateIn = test_input($_POST["cosmInOut_dateIn"]);
  $cosmInOut_qtyIn = test_input($_POST["cosmInOut_qtyIn"]);
  $cosmInOut_expire = test_input($_POST["cosmInOut_expire"]);
  $cosmInOut_priceIn = test_input($_POST["cosmInOut_priceIn"]);
  $cosmInOut_4sale = test_input($_POST["cosmInOut_4sale"]);
  $cosmInOut_dateOut = test_input($_POST["cosmInOut_dateOut"]);
  $cosmInOut_qtyOut = test_input($_POST["cosmInOut_qtyOut"]);
  $cosmInOut_priceOut = test_input($_POST["cosmInOut_priceOut"]);
 }

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

$inserted = 0;
while ($cosmInOut_qtyIn > $inserted) {
$sql = "INSERT INTO cosmInOut (cosmInOut_name, cosmInOut_dateIn, cosmInOut_expire, cosmInOut_priceIn, cosmInOut_4sale, cosmInOut_dateOut, cosmInOut_qtyOut, cosmInOut_priceOut)" .
        "VALUES('{$cosmInOut_name}', '{$cosmInOut_dateIn}', '{$cosmInOut_expire}', '{$cosmInOut_priceIn}', '{$cosmInOut_4sale}', '{$cosmInOut_dateOut}', '{$cosmInOut_qtyOut}', '{$cosmInOut_priceOut}')";
    $inserted++;
    }
if ($conn->query($sql) === TRUE) {
    include('../head.php');
    echo '
        <script> some script</script> 
    ';
    include('../footer.php');

} else {
    echo 'Error' . $conn->error;
}

$conn->close();
?>

显然,我的while功能不起作用。我该如何解决? 感谢

1 个答案:

答案 0 :(得分:0)

此时您将重复创建插入字符串$ cosmInOut_qtyIn次数&amp;然后只插入一次。

你可以在循环之外创建一次和一次的查询字符串。然后在循环内重复查询。

另一个解决方案是将要添加$ cosmInOut_qty的次数(逗号分隔)的值附加到查询字符串&amp;然后只运行一次查询。类似的东西:

$sql = "INSERT INTO cosmInOut (cosmInOut_name, cosmInOut_dateIn, cosmInOut_expire, cosmInOut_priceIn, cosmInOut_4sale, cosmInOut_dateOut, cosmInOut_qtyOut, cosmInOut_priceOut) VALUES ";
$sqlv = "('{$cosmInOut_name}', '{$cosmInOut_dateIn}', '{$cosmInOut_expire}', '{$cosmInOut_priceIn}', '{$cosmInOut_4sale}', '{$cosmInOut_dateOut}', '{$cosmInOut_qtyOut}', '{$cosmInOut_priceOut}')";

$inserted = 0;
while ($cosmInOut_qtyIn > $inserted)
{
    if ($inserted > 0)
        $sql = $sql . ",";
    $sql = $sql . $sqlv;
    $inserted++;
}