1

我刚刚开始使用 PDO,但我正在慢慢掌握它。我想知道如何使下拉菜单或列表框将数据填充到页面上的字段中。我已经通过查找 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

4

2 回答 2

12

答案很简单:不要通过 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>
于 2013-05-29T12:01:01.117 回答
1
    //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 -->
于 2018-02-24T10:04:41.013 回答