使用PDO :: FETCH_ASSOC填充下拉列表返回bool(false)

时间:2018-02-25 02:26:38

标签: php sql

我正在尝试在PHP中填充下拉列表,但在下拉列表后它返回bool(false)

start.php     

$db = new PDO('mysql:host=localhost;dbname=hospital','root','');

?>

这是我要使用的数据和输出的下拉列表     

require 'start.php';

$doctorsQuery = "
    SELECT 
        specialties.SID,
        specialties.name,
        doctors.firstname,
        doctors.lastname,
        doctors.middleinitial 
    FROM specialties
    LEFT JOIN doctors
    ON specialties.SID = doctors.SID";

 $doctors = $db->query($doctorsQuery);

?>

这是针对下拉列表中的选择选项

<?php foreach($doctors->fetchAll() as $specialty): ?>
  <option value="<?php echo $specialty['SID']; ?>"><?php echo 
$specialty['name']; ?></option>
<?php endforeach; ?>    

我正在尝试查看此处的数据但显示bool(false)

<?php if(isset($_GET['specialty'])){
$doctorQuery = "
{doctorsQuery}
WHERE specialties.SID == :S_ID";

$doctor = $db->prepare($doctorQuery);
$doctor->execute(['S_ID' => $_GET['specialty']]);

    $selectedDoctor = $doctor->fetch(PDO::FETCH_ASSOC);

    var_dump($selectedDoctor);
}
?>

1 个答案:

答案 0 :(得分:0)

它喜欢你使用带有命名占位符的prepare语句,试试这个:

$doctor->execute([':S_ID' => $_GET['specialty']]); // you forget ":"

而且......我建议您在获取之前检查行数

if ($doctor->rowCount() === 1) {
    $selectedDoctor = $doctor->fetch(PDO::FETCH_ASSOC); // so you will not get false

    // your logic
} else {
    // when S_ID not found

}