使用下拉列表将数据发送到数据库

时间:2015-07-24 02:45:50

标签: php mysql

我目前正在学习PHP,而我正在尝试做的是使用HTML下拉列表为用户选择排名。

insert.php:

<?php
$tUsers_Select = "SELECT * FROM users LEFT JOIN ranks ON ranks.rankName = users.rank";
$tRanks_Select = "SELECT * FROM ranks";
$tUsers_Select_Query = mysql_query($tUsers_Select);
$tRanks_Select_Query = mysql_query($tRanks_Select);

?>
<form action="insertData.php" method="post">
<select name="ranks">
    <option value="0" selected="selected">Select rank</option>
<?php
while ($ranks_item = mysql_fetch_array($tRanks_Select_Query, MYSQL_ASSOC)) {
    $rankID = $ranks_item['rankID'];
    $value = $ranks_item['value'];
    $rankName = $ranks_item['rankName'];
    $rankOrder = $ranks_item['rankOrder'];

    echo '<option value="'.$rankOrder.'" name="'.$value.'">'.$rankName.'</option>';
}

while ($users_item = mysql_fetch_array($tUsers_Select_Query, MYSQL_ASSOC)) {
    $ID = $users_item['ID'];
    $rank = $users_item['rank'];
    $username = $users_item['username'];
    $email = $users_item['email'];
    $password = $users_item['password'];
}

?>

</select>

<input type="hidden" name="rankID">
<input type="hidden" name="ID">
<input type="text" name="username">
<input type="email" name="email">
<input type="password" name="password">

<button type="submit">Submit</button>

</form>

insertData.php:

<?php

$rank = $_POST['rank'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];

$insertUser = "INSERT INTO users (";
$insertUser .= "rank, ";
$insertUser .= "username, ";
$insertUser .= "email, ";
$insertUser .= "password) ";
$insertUser .= "VALUES (";
$insertUser .= "'".$rank."', ";
$insertUser .= "'".$username."', ";
$insertUser .= "'".$email."', ";
$insertUser .= "'".$password."')";

echo "<br />".$insertUser;

if (!isset($rank)) {
    echo "Rank is not set";
    echo '<br /><a href="insert.php">Go back</a><br />';
}   else {
    echo "Rank is set";
    mysql_query($insertUser);
}

?>

当我运行此代码时,收到一条错误消息:

注意:未定义的索引等级

用户数据库表:

ID | rank | username | email | password

排名数据库表:

rankID | value | rankName | rankOrder
-------------------------------------
1      | rank  | Manager  | 3
2      | rank  | Admin    | 2
1      | rank  | Editor   | 1

如果您需要更多详情,请发表评论。

1 个答案:

答案 0 :(得分:0)

您的<select>代码名称为<select name="ranks">,而您发布的内容为$rank = $_POST['rank'];,应为$rank = $_POST['ranks'];