dongwen5351
2015-07-24 02:45
浏览 24
已采纳

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

I'm currently learning PHP and what I'm trying to do is use a HTML dropdown to select a rank for a user.

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);
}

?>

When I run this code, I get an error message which is:

Notice: Undefined index rank

Users Database tables:

ID | rank | username | email | password

Ranks Database tables:

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

If you need any more details, please comment.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doudu161481 2015-07-24 02:50
    已采纳

    you have <select> tag name as <select name="ranks"> and you are posting $rank = $_POST['rank'];, it should be $rank = $_POST['ranks'];

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题