Как заполнить несколько выпадающих списков mysql / php, используя разные столбцы таблицы

0

EDIT: возникает проблема с дополнительным "или каким-то синтаксисом при добавлении второго предложения select.

Таким образом, я работаю над проектом php, используя базу данных примеров mysql adventureworks. В настоящее время на этой странице отображается название сотрудников, которое вы можете выбрать из раскрывающегося списка, заполненного всеми возможными заголовками для фильтрации через сотрудников. Тем не менее, я хотел добавить второй блок с полом, чтобы кто-то мог фильтровать через заголовок и пол и получать всех возможных сотрудников.

Я попробовал несколько вещей, но они обычно заканчивают разбивку страницы.

Heres первый файл: search.php

<?php
   // Connect to the database

   if (!include('connect.php')) {
      die('error finding connect file');
   }

   $dbh = ConnectDB();
?>
<html>

<head>
   <link href='http://fonts.googleapis.com/css?family=Cuprum' 
rel='stylesheet' type='text/css'>
   <link href="https://fonts.googleapis.com/css?family=Amaranth" 
rel="stylesheet">
   <link href="https://fonts.googleapis.com/css?family=Roboto+Mono" 
rel="stylesheet">
         <link href="main.css" rel="stylesheet">
   <title>Table Results</title>
</head>

<body>
<div class="content">

<h1>Search Adventureworks Employees</h1>
<p>Select two parameters and search information from the
AdventureWorks Database.</p>

<div class="form">
<form action="listTable.php" method="get">

<?php

   // Get the full list of titles from Employee Table
  $sql =  "SELECT Distinct title FROM adventureworks.employee";
  $stmt = $dbh->prepare($sql);
  $stmt->execute();

 // Prep drop down control
  echo "<label for='title'>Select title: </label>\n";
  echo "<select id='title' name='title'>\n";

 // Put titles in the options
  foreach ($stmt->fetchAll() as $titles) {
     echo "<option value='" . $titles['title'] . "'>" .
$titles['title'] . "</option>\n";
  }
   // End dropdown
  echo "</select>";

  // Get the full list of genders from employee table
  $sql3 = "Select Distinct gender FROM adventureworks.employee";
  $stmt = $dbh->prepare($sql3);
  $stmt->execute();

  //Prep dropdown
  echo "<label for ='gender'>Select Gender: </label>\n";
  echo "<select id='gender' name = 'gender'>\n";

  // Put genders in the options
  foreach($stmt->fetchAll() as $genders) {
     echo "<option value ='" . $genders['gender'] . "'> .
$genders['gender'] . "</option>\n";
   }
  //end dropdown and submit
  echo "</select>&nbsp;&nbsp;&nbsp;&nbsp;<input type='submit' 
value='Submit'>\n</form>\n</div>";
?>

</div>

</body>
</html>

И heres второй php файл: listTable.php

<?php
   // Connect to the database

   if (!include('connect.php')) {
      die('error finding connect file');
   }

   $dbh = ConnectDB();
?>
<html>

<head><link href='http://fonts.googleapis.com/css?family=Cuprum' 
rel='stylesheet' type='text/css'>
   <link href="https://fonts.googleapis.com/css?family=Amaranth" 
rel="stylesheet">
   <link href="https://fonts.googleapis.com/css?family=Roboto+Mono" 
rel="stylesheet">
     <link href="main.css" rel="stylesheet">
   <title>Table Results</title>
</head>

 <body>
 <div class='content'>

<?php
 // Get table name from querystring
    if (!isset($_GET["title"])) {
      echo "No Title Selected";
    }
   else {

      $title=$_GET["title"];
      echo "<h1>Listing of Employees</h1>\n";

      $sql1 = "SELECT column_name FROM information_schema.columns ";
      $sql1 .= "WHERE table_name = 'employee'";
      $stmt = $dbh->prepare($sql1);
      $stmt->execute();
      $cols = $stmt->rowCount();

  // Prep table
  $tableHTML = "<table>\n<thead>\n<tr>\n";

  // Table headings (column names)
  foreach ($stmt->fetchAll() as $columns) {
     $tableHTML .= "<th>" . $columns['column_name'] . "</th>\n";
  }

  // Prep table body
  $tableHTML .= "</tr>\n</thead>\n<tbody>\n";

  // Table body (column values)
  $sql2 = "SELECT * FROM adventureworks.employee e";
  $sql2 .= " Where title like '$title'";
  $stmt = $dbh->prepare($sql2);
  $stmt->execute();
  echo $stmt->rowCount() . " rows retrieved<br/><br />\n";

  foreach ($stmt->fetchAll() as $rows ) {
     $tableHTML .= "<tr>\n";
     for ($i = 0; $i < $cols; $i++) {
        $tableHTML .= "<td>" . $rows[$i] . "</td>\n";
     }
     $tableHTML .= "</tr>\n";
  }

  // End table
  $tableHTML .= "</tbody>\n</table>\n";
  echo $tableHTML;
  echo "<div class='code'><br />" . $sql1 . "<p>" . $sql2 . "</div>\n";
 } 
?>

</div>
</body>
</html>

Я понимаю, что мне пришлось бы изменить во втором файле, чтобы получить результаты, которые я хочу, но им не удалось просто заполнить второй снимок в первом файле. Любая помощь будет оценена по достоинству. Благодарю.

  • 0
    Есть ли в списке заголовков идентификатор? Создание второго <выбора с полами не должно быть проблемой. вам нужно передать эти два значения через get или session на другую страницу. Вы можете проверить, получаете ли вы все get-значения, используя print_r ($ _ GET);
  • 0
    @ Бернхард: get get - это не моя проблема, я просто не знаю, с чего начать второй оператор select без получения синтаксических ошибок.
Показать ещё 2 комментария
Теги:

1 ответ

0
Лучший ответ

Вы пропустили двойную кавычку в search.php

// Put genders in the options
  foreach($stmt->fetchAll() as $genders) {
     echo "<option value ='" . $genders['gender'] . "'>" .
    $genders['gender'] . "</option>\n";
   }
  • 0
    Не могу поверить, что я пропустил это. Спасибо!

Ещё вопросы

Сообщество Overcoder
Наверх
Меню