doufan6886
doufan6886
2014-05-26 19:04
浏览 183
已采纳

将select标签中的选定值插入数据库

I have a database table with the names and locations of schools. Looks like this

id      name                           location
1   Federal University of tech        California
2.  Massachusetts Inst of tech            Boston

I'm populating a select tag with the names of these schools using this table. And it works fine. Each user is supposed to select his/her school when creating his/her profile. However when the form is submitted, only the first word in the school name gets inserted. e.g for Federal University of tech; only Federal is inserted into the database and for Massachusetts Inst of tech only Massachusetts is inserted - and so on - as opposed to the full name of the school. How do i get the full names of the selected school inserted? The code(page.php):

<?php
//Getting names of schools to populate select tag

$stmt = $db->query("SELECT name from schools order by name ASC");

if($_SERVER['REQUEST_METHOD'] == "POST"){
$major = $_POST['major'];
$university = $_POST['university'];
$email = $_POST['email'];

$stmts = $db->prepare("INSERT INTO profile (university, major email)") VALUES (:university, :major, :email);
$stmts->execute(array(':university' => $university, ':major' => $major, ':email' => $email));
}

?>

//THE HTML FORM
<form action = "page.php" method = "post">

<label>University:

<?php
echo '<select title = "Select one" name= "university"></select>';
echo '<option value="">--please select--</option>';

while ($rows = $stmt->fetch[PDO::FETCH_ASSOC])
echo '<option value = '.$rows['name'].'>'.$rows['name'].'</option>';

echo '</select>';

?>
//other form elements
</label>
</form>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • du90093662774150
    du90093662774150 2014-05-26 19:27
    已采纳

    I think the problem lies in the the way you have written value attribute for the option tag. The suggestion is to put values-with-spaces in double quotes.

    Like:

    echo '<option value = "Massachusetts Inst of tech">Massachusetts Inst of tech</option>';
    


    But what is getting passed is this because double quotes have been neglected:

    echo '<option value = "Massachusetts">Massachusetts Inst of tech</option>';
    

    You might want to check out this line:

    echo '<option value = '.$rows['name'].'>'.$rows['name'].'</option>';
    

    and correct with this one:

    echo '<option value = "'.$rows['name'].'">'.$rows['name'].'</option>';
    
    点赞 评论

相关推荐