我试图从下拉框插入用户输入到我的数据库。我使用此代码的形式动态地从数据库生成选项。从player1一直到player11都是这样,但都使用相同的代码所以为了节省空间,我将只包含player1的一个示例:
<form action="teamCreate.php" onsubmit="return validateForm();" name="teamCreation" method="post">
<table>
<tr>
<td>
Player 1:
</td>
<td>
<select id="player1" name="player1">';
$sql = mysql_query("SELECT playerName FROM Player");
while ($row = mysql_fetch_array($sql))
{
echo "<option value='"player'">" . $row['playerName'] . "</option>";
}
echo '</select>
</td>
</tr>
</table>
我在teamcreate。php中是这样做的:
$player=array(); //Creates an array of players, using the values posted from editTeam.php
$player[1]=$_POST['player1'];
$player[2]=$_POST['player2'];
$player[3]=$_POST['player3'];
$player[4]=$_POST['player4'];
$player[5]=$_POST['player5'];
$player[6]=$_POST['player6'];
$player[7]=$_POST['player7'];
$player[8]=$_POST['player8'];
$player[9]=$_POST['player9'];
$player[10]=$_POST['player10'];
$player[11]=$_POST['player11'];
$teamName = $_SESSION['teamName'];
$counter=1;
while ($counter < 12) //Creates a loop that goes through the player array, adding them to the database under the user's team name
{
$currentPlayer = $player['$counter'];
mysql_query("INSERT INTO PlayerListing(teamName, playerName)VALUES('$teamName', '$currentPlayer')");
$counter = $counter + 1;
}
当我查看数据库中的结果时,所有添加的行都正确设置了teamName列,但是playerName列是空白的。这个问题我已经想了好几个小时了,还是不明白是什么问题。
谢谢,沃尔夫。
看一下这段代码:
while ($counter < 12) //Creates a loop that goes through the player array, adding them to the database under the user's team name
{
$currentPlayer = $player['$counter'];
mysql_query("INSERT INTO PlayerListing(teamName, playerName)VALUES('$teamName', '$currentPlayer')");
$counter = $counter + 1;
}
当您分配您的$currentPlayer
时,您使用单引号并在其中包含变量名称。看起来你想在这里表示$counter
的值,但是你不能用单引号这样做,只有双引号会为你插入变量值。要解决这个问题,你必须完全删除引号(这是我建议的),或者用双引号把变量括起来。
while ($counter < 12) //Creates a loop that goes through the player array, adding them to the database under the user's team name
{
$currentPlayer = $player[$counter];
mysql_query("INSERT INTO PlayerListing(teamName, playerName)VALUES('$teamName', '$currentPlayer')");
$counter = $counter + 1;
}
问题是你的索引$counter
(字面上,不是作为一个变量)不包含任何值,因此没有值被插入到数据库中。