将15行相同数据插入数据库

时间:2015-04-20 12:50:01

标签: php mysql mysqli

我有15行相同的数据要重复插入,有没有办法处理它而不是重复15个单独的查询?

我目前的1行代码如下所示

$FirstName1=mysqli_real_escape_string($con,$_POST['FirstName1']);
$Surname1=mysqli_real_escape_string($con,$_POST['Surname1']);
$Position1=mysqli_real_escape_string($con,$_POST['Position1']);
$Value1=mysqli_real_escape_string($con,$_POST['Value1']);

mysqli_query($link,"INSERT INTO Players (FirstName, Surname, Position, Value) VALUES ('$FirstName1', '$Surname1', '$Position1', '$Value1')") or die(mysqli_error($link));

有没有办法运行foreach来首先检查数据是否存在,然后循环并运行插入?每个字段的数字,因此“FirstName1”例如将从1-15开始。

2 个答案:

答案 0 :(得分:2)

您可以使用如下。

    $message = "";    
    for($i=1;$i<=15;$i++){

            $nameElemenet = "FirstName".$i;
            $FirstName = mysqli_real_escape_string($con,$_POST[$nameElemenet]);

            $surNameElemenet = "Surname".$i;
            $Surname = mysqli_real_escape_string($con,$_POST[$surNameElemenet]);

            $positionElemenet = "Position".$i;
            $Position = mysqli_real_escape_string($con,$_POST[$positionElemenet]);

            $valueElemenet = "Value".$i;
            $Value = mysqli_real_escape_string($con,$_POST[$valueElemenet]);

            if($nameElemenet !="" && $Surname !="" && $positionElemenet !="" && $Value !="" ){
                mysqli_query($link,"INSERT INTO Players (FirstName, Surname, Position, Value) VALUES ('$FirstName', '$Surname', '$Position', '$Value')") or die(mysqli_error($link));
            }else{
                $message .= "All filed values are required.";
            }
        }

答案 1 :(得分:0)

使用while循环:

<?php
$x = 1;

while($x <= 15) {
    mysqli_query($link,"INSERT INTO Players (FirstName, Surname, Position, Value) VALUES ('$FirstName1', '$Surname1', '$Position1', '$Value1')") or die(mysqli_error($link));
    $x++;
}
?>