简体   繁体   English

通过php输入表单一次将多行插入sql数据库

[英]insert multiple rows into sql database at once through php input form

I am trying to record the results of a car race, but I want to be able to enter all of the results for the race at once (rather than doing it one by one) but I just cannot seem to get it to work.我正在尝试记录赛车的结果,但我希望能够一次输入比赛的所有结果(而不是一个一个地输入),但我似乎无法让它发挥作用。

Code below:代码如下:

INPUT FORM:输入表格:

{
    $reID = $row['reID'];
    $racerID = $row['racerID'];

    echo "<tr>";
    echo "<td>$reID<input type='hidden' name='reID' value='$reID'>"; 
    echo "<td>$racerID<input type='hidden' name='racerID' value='$racerID'>"; 

    echo"<td><input type='text' name='rank'>";
    echo"<td><input type='text' name='timetaken'>";     

}

SQL INSERT FORM: SQL 插入表格:

$rank=$_POST['rank'];
$timetaken=$_POST['timetaken'];
$reID=$_POST['reID'];
$racerID=$_POST['racerID']; 

    $sql = mysql_query("INSERT INTO Racing (rank, timetaken, reID, racerID) VALUES ('$rank', '$timetaken', '$reID', '$racerID')");
    $result = mysql_query($sql);

How this works is, I will select a race, then a specific event within that race, then that will display all the racers and I can enter their rank and time taken.这是如何工作的,我将选择一场比赛,然后选择该比赛中的特定事件,然后将显示所有赛车手,我可以输入他们的排名和所用时间。 At the same time the hidden inputs (racer no and raceevent will go into the database for each result too).同时隐藏的输入(赛车手编号和比赛事件也将进入数据库以获取每个结果)。

So I am trying to just enter all the ranks and timetaken for all racerIDs at once, can someone help me complete that please.所以我想一次输入所有 RacerID 的所有等级和时间,有人能帮我完成吗?

Thanks.谢谢。

EXTRA:额外的:

$reID = $_GET['reID'];
$result = mysql_query("SELECT * FROM RaceEventRacer WHERE reID = $reID");

while ($row = mysql_fetch_assoc($result))

First of all u have to fix some issues with ur php form generation...首先你必须解决你的 php 表单生成的一些问题......

all of ur input elements are going to have the same name attribute... correct it first您的所有输入元素都将具有相同的 name 属性...首先更正它

-use something like this - 使用这样的东西

$cv=0;

while () {

    .......................
    .......................
    echo "<input name='racer_'.$cv>";  // in each repetition new name value, not the same



    $cv++;
}

Instead of having name='reID' you should have name='reID[]', the same withthe other fields.您应该有 name='reID[]',而不是 name='reID',与其他字段相同。 And the future code would look like this:未来的代码将如下所示:

$ranks = $_POST['rank'];
$timetakens = $_POST['timetaken'];
$reIDs = $_POST['reID'];
$racerIDs = $_POST['racerID']; 

$sql = "INSERT INTO Racing (rank, timetaken, reID, racerID) VALUES";
$values = array();
foreach($ranks as $key => $rank) {
    $values[] = "('$rank', '{$timetakens[$key]}', '{$reIDs[$key]}', '{$racerIDs[$key]}')";
}
$sql .= implode(', ', $values);
    $query = mysql_query($sql);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM