对不同的变量进行多次foreach ?数据库中的值重复


Multiple foreach for different variables? Values duplicating in database

我正在测试一个textarea盒子及其相应的foreach代码。工作的成功。基本上,代码获取文本区域框中的每个值,并将每个值插入到数据库中的单独行中。

但是我想复制这个,因为我有多个文本区域框。

任何人都可以验证以下代码吗?

$text = trim($_POST['BachelorsDegrees']);
$textAr = explode("'n", $text);
$textAr = array_filter($textAr, 'trim'); // remove any extra 'r characters left behind
$textCert = trim($_POST['Certifications']);
$textArCert = explode("'n", $textCert);
$textArCert = array_filter($textArCert, 'trim'); // remove any extra 'r characters left behind
$textDip = trim($_POST['Diplomas']);
$textArDip = explode("'n", $textDip);
$textArDip = array_filter($textArDip, 'trim'); // remove any extra 'r characters left behind
$textAD = trim($_POST['AssociateDegrees']);
$textArAD = explode("'n", $textAD);
$textArAD = array_filter($textArAD, 'trim'); // remove any extra 'r characters left behind
$textMD = trim($_POST['MastersDegrees']);
$textArMD = explode("'n", $textMD);
$textArMD = array_filter($textArMD, 'trim'); // remove any extra 'r characters left behind
$textDD = trim($_POST['DoctorateDegrees']);
$textArDD = explode("'n", $textDD);
$textArDD = array_filter($textArDD, 'trim'); // remove any extra 'r characters left behind
$textSD = trim($_POST['SpecialDegreePrograms']);
$textArSD = explode("'n", $textSD);
$textArSD = array_filter($textArSD, 'trim'); // remove any extra 'r characters left behind

foreach ($textAr as $BachelorsDegrees)
{
    foreach ($textArCert as $Certifications)
    {
    foreach ($textArDip as $Diplomas)
    {
    foreach ($textArAD as $AssociateDegrees)
    {
    foreach ($textArMD as $MastersDegrees)
    {
    foreach ($textArDD as $DoctorateDegrees)
    {
    foreach ($textArSD as $SpecialDegreePrograms)
    {
    mysql_query("INSERT INTO College_Courses (Name, BachelorsDegrees, Certifications,Diplomas,AssociateDegrees,MastersDegrees,DoctorateDegrees,SpecialDegreePrograms) VALUES ('$Name','$BachelorsDegrees', '$Certifications', '$Diplomas', '$AssociateDegrees', '$MastersDegrees', '$DoctorateDegrees','$SpecialDegreePrograms')") or die(mysql_error()) ;
    }
    }
    }
    }
    }
    }
} 
}
else
{
echo mysql_error();
}

这是它们在数据库中的样子:

DoctorateDegrees似乎工作得很好,但它复制了自己。

如果我把

<p>Onion1<br>
Onion2<br>
Onion3</p>

放到文本框中,它们都有自己的行,但是会像这样重复:

<p>Onion1<br>
Onion2<br>
Onion3</p>
<p>Onion1<br>
Onion2<br>
Onion3</p>
<p>Onion1<br>
Onion2<br>
Onion3</p>

其他列,例如,BachelorsDegrees(在我插入额外的foreach代码之前工作良好)将只重复第一个值:

<p>Onion1<br>
<p>Onion1<br>
<p>Onion1<br>

MastersDegrees将重复相同的值若干次:

<p>Onion1<br>
<p>Onion1<br>
<p>Onion1<br>
Onion2<br>
Onion2<br>
Onion2<br>
Onion3<br>
Onion3<br>
Onion3<br>

任何想法?

注意:BachelorsDegrees 工作之前,当我在添加其他列之前测试它。

我强烈建议您将College_Courses表拆分为几个较小的表。可能每个专栏一个(上面提到的)。除非我遗漏了什么。数据库设计的经验法则是不要在同一个表中捆绑许多不同的属性。

如果你仍然想坚持一个表的方法,你应该分开你的foreach循环,并在每个循环中做INSERT查询,而不是像现在这样嵌套它们。但是,您最终会得到一个巨大的表,其中有很多未使用的空间。