通过pdo代码填充下拉菜单

时间:2013-05-29 11:31:01

标签: php sql-server pdo dreamweaver

好吧所以我只是盯着使用pdo但我慢慢得到它的悬念我想知道如何制作一个下拉菜单或列表pox将数据填充到页面上的字段我已启动代码通过查找pdo指南等,但我很难找到解决方案。也对不整洁的代码感到抱歉,但我又是整个编程场景的新手

在这里感谢建议到目前为止我的代码是: 这是连接字符串:

<?php
    session_start();

    if(!isset($_SESSION["user_id"])){
        header("location:../Pages/login.html");
    }


    //databse connection Sting
    $connection = new PDO("sqlsrv:server=servername;Database=databasename", "username",                     "password"); 

    //insertion function
    $smt = $connection->prepare('select exam_id From exam');



?>

还包括我的会话cookie,但效果很好,这是我到目前为止的下拉框的人口。

 <select name="lst_exam" id="lst_exam">

       <?php

            $smt->execute();
            while ($row = $smt->fetch()){
                echo "<option>" . $row["exam_id"] . "</option>";
            }
            $connection = null;
        if(isset($_POST["lst_exam"]));  

        ?>
    </select>

我试图填写的文本框是txt_exam_id,txt_location,txt_date_taken,txt_exam_taken,txt_grade_recieved

2 个答案:

答案 0 :(得分:10)

答案很简单:不通过pdo代码填充下拉菜单

这是完全不同的问题,不应该在代码中混淆。

将您的代码分为两部分:

  • PDO代码
  • 填充传统数组代码中的任何菜单。

单独编写和调试这些部分。

$smt = $connection->prepare('select exam_id From exam');
$smt->execute();
$data = $smt->fetchAll();

现在你的考试存储在$ data数组中。

<select name="lst_exam" id="lst_exam">
<?php foreach ($data as $row): ?>
    <option><?=$row["exam_id"]?></option>
<?php endforeach ?>
</select>

答案 1 :(得分:0)

    //USING PDO   

 $ID=trim($_GET['id']);
    $result = $DB_con->prepare("select userID, firstName, lastName, gender, telNo, userEmail, userName, contactAddress, case when userStatus = 'Y' then 'TRUE' ELSE 'FALSE' end as userStatus, case when state = 1 then 'ACTIVE' else 'IN-ACTIVE' end as state, department.name as department from users JOIN department on department.id = users.department where userID=:get_header LIMIT 1");
    $result->execute(array(":get_header"=>$ID));
    $result->execute();
    for($i=0; $row = $result->fetch(); $i++){
    $id=$row['userID'];
    ?>

    $sql_g = "Select id, name from gender";
    $gend = $DB_con->prepare($sql_g);
    //Execute the statement.
    $gend->execute();
    //Retrieve the rows using fetchAll.
    $gend_lists = $gend->fetchAll(PDO::FETCH_ASSOC);


     //HTML AND PHP
    <div class="col-sm-3">
          <div class="form-group">
              <label class="control-label">Gender</label>
                 <?php $value = $row["gender"]; ?>
                 <select name="gender_test" class="form-control">
                      <?php foreach($gend_lists as $id => $option) { ?>
                        <option value="<?php echo $id["id"] ?>"<?php
                      if($id["id"] == $value) {
                  echo " selected";
             } ?>><?php echo $option["name"] ?></option>
          <?php } ?>
       </select>
     </div><!-- form-group -->
</div><!-- col-sm-6 -->