如何从下拉列表中选择后获取数据

时间:2014-09-29 10:13:39

标签: php mysql

我想从下拉列表中获取数据。就像我从下拉列表中选择员工ID 40一样,它将从该员工的数据库中获取数据并显示在文本框中。

这是我的下拉代码。请帮助我如何获得所选值。

<?php
    $con=mysqli_connect("localhost","root","","hct_db");
    // Check connection
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
?>

 <label>Select Employee ID</label>
     <select class="form-control" name="employee_id">
         <?php 
         $result = mysqli_query($con,"SELECT employee_id FROM employee order by employee_id");

         while($row = mysqli_fetch_array($result)) 
             echo "<option value='" . $row['employee_id'] . "'>" . $row['employee_id'] . "</option>";
         ?>
     </select>

6 个答案:

答案 0 :(得分:1)

<?php
if(isset($_REQUEST['submit']))
{
  $value=$_POST['employee_id'];
  $query = mysql_query($con,"SELECT employee_name FROM employee where employee_id=$value");
  $result=mysql_fetch_array($query);
  $emp_name=$result['employee_name'];
}
?>

<form action="" method="post" name="form">
 <label>Select Employee ID</label>
   <select class="form-control" name="employee_id">
    <?php $result = mysqli_query($con,"SELECT employee_id FROM employee order by employee_id");
 while($row = mysqli_fetch_array($result)) 
   echo "<option value='" . $row['employee_id'] . "'>" .$row['employee_id'] . "</option>";
 ?>
  </select>
<input type="submit" name="submit" value="submit">
</form>
 <input type="text" value="<?=$emp_name?>" name="emp_name"/>

check this code as your need

答案 1 :(得分:1)

首先给你一些id选择这样的选项:

<select class="form-control" name="employee_id" id='employee'>

添加如下文本框:

<input type='text' name='emp_name' id='emp_name' />

比使用jquery和ajax这样:

$('#employee').change(function(){
    var selected_id = $(this).val();
    var data = {id:selected_id};
    $.post('getemp_name.php',data,function(data){
         $('#emp_name').val(data);
    });
});

<强> getemp_name.php

if(isset($_POST['id'])){
    //fire query using this id and get the name of employee and echo it
    echo $emp_name;
}

答案 2 :(得分:1)

使用此示例,您可以通过单击Here轻松地学习如何从下拉列表中获取数据。该存储库包含所有代码

答案 3 :(得分:0)

要获取所选值,您必须在用户提交表单后到达$_GET$_POST超级用户。

所以,在提交之后,如果你发帖,请把它作为:

<?php 
$employee_id = $_POST['employee_id']; ?>

如果你获得:

<?php 
$employee_id = $_GET['employee_id']; ?>

答案 4 :(得分:0)

onChange

上应用以下功能
function myFunction(mySelect) {
        var x = document.getElementById("mySelect").value;
        document.getElementById("demo").innerHTML = "You selected: " + x;
    }

example

答案 5 :(得分:0)

这取决于你想要什么。如果要在查询后使用查询中的所选ID,可以使用以下查询:

    "SELECT   *
     FROM     `employee`
     WHERE    `employee`.`employee_id` = " . (int) $_POST['employee_id'] . "
     LIMIT    1"

假设您在表单中使用post方法。