将选项从下拉菜单存储到数据库中

时间:2013-12-01 01:14:35

标签: php html forms

我的html代码中有以下表单字段:

<select class="secret_question">
                     <option value ="1">The name of the city where you were born</option>
                     <option value ="2">The name of your first pet</option>
                     <option value ="3">What is your mother's maiden name</option>
                  </select>

问题:如何将所选选项存储到数据库中。我已经能够使用以下代码将名称,email-id等常规字段存储到数据库中:

$firstname = $_REQUEST['firstname'];
    $lastname = $_REQUEST['lastname'];
$stmt = $dbh->prepare("INSERT INTO users (firstname,lastname) VALUES ('$firstname', '$lastname')");

我为选择列表尝试了相同的技术,但它给了我"undefined index"错误

1 个答案:

答案 0 :(得分:0)

如果表单元素不是“已命名”,则会出现undefined index错误。

您需要为<select>命名,如下所示:

<select class="secret_question" name="secret_question">

然后使用$secret_question = $_REQUEST['secret_question'];

如下:

$firstname = $_REQUEST['firstname'];
$lastname = $_REQUEST['lastname'];
$secret_question = $_REQUEST['secret_question'];
$stmt = $dbh->prepare("INSERT INTO users (firstname,lastname,secret_question) 
VALUES ('" . $firstname . "', '" . $lastname . "', '" . $secret_question . "')");

命名数据库列secret_question

使用以下约定更安全:

'" . $firstname . "'代替'$firstname'

但是,您可能希望使用输入字段而不是<select>,因为人们可能会自己输入答案,具体取决于您的设置。