我刚刚开始使用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_received
答案很简单:不要通过pdo代码填充下拉菜单
这是完全不同的事情,不应该在代码中混合。
把你的代码分成两部分:
- <
- PDO代码/gh>
- 从传统的数组代码中填充任何菜单。
分别编写和调试这些部分。
$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>
//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 -->