Флажки, форма отправки и как правильно использовать array_fill в цикле? - PullRequest
0 голосов
/ 05 мая 2018

У меня есть форма, в которой пользователь может внести некоторые изменения в шкалу оценок. Они также могут выбрать применение этих изменений к 1 или более записям (номерам секций классов). Вот скриншот моей формы вместе с кодом ниже:

Form Screenshot

Когда я нажимаю флажки, мне нужно вставить данные из формы в базу данных, используя каждый из номеров разделов из флажков. Поскольку массив флажков содержит только 3 значения, он не завершает вставку всех строк с номерами разделов. В моем коде вы увидите, что я пытался использовать array_fill, но я явно не использую это правильно или в нужном месте.

Вот как правильно выглядит моя таблица базы данных перед отправкой формы: http://sqlfiddle.com/#!9/015a20/1

Вот так выглядит таблица базы данных после отправки моей формы: http://sqlfiddle.com/#!9/15e40a/1

Вот мой тестовый вывод переменной, которая вызывает у меня проблемы ($ SectionNumber):

5011 is SectionNumber
5013 is SectionNumber
5099 is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
5011 is SectionNumber
5013 is SectionNumber
5099 is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
5011 is SectionNumber
5013 is SectionNumber
5099 is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber
is SectionNumber

Мне нужно / ожидается, что вывод покажет, что «5011 is SectionNumber» повторяется 11 раз, затем «5013 is SectionNumber» и, наконец, «5099 is SectionNumber» 11 раз.

Форма HTML:

https://jsfiddle.net/keusv75a/

<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" name="snum">
   <p>
      Select the section for which you'd like to display the grading scale below:<br />
      <select name="snum">
         <?php
            $stmt4 = $connection->prepare("SELECT DISTINCT c.SectionNumber FROM Courses c, Assignments a WHERE a.SectionNumber = c.SectionNumber
            ") or die($connection->error);
            $stmt4->execute();
            $result4 = $stmt4->get_result();

            while ($row4 = $result4->fetch_assoc()):
            ?>
         <option value="<?php echo $row4['SectionNumber']; ?>" <?php
            if ($_POST['snum'] == $row4['SectionNumber']) {
                echo "selected";
            } ?>><?php echo $row4['SectionNumber']; ?></option>
         <?php
            endwhile; ?> 
      </select>
      <input class="btn btn-sm btn-primary" type="submit" value="Show Me">
   </p>
</form>
<form action="admin_grading_scale2.php" method="post">
   <p>Which section(s) would you like to apply this grading scale to?<br>
      <?php $stmt4 = $connection->prepare("SELECT DISTINCT SectionNumber FROM Courses
         ") or die($connection->error);
         $stmt4->execute();
         $result4 = $stmt4->get_result();

                      while ($row4 = $result4->fetch_assoc()):
         ?>
      <label>
      <input type="checkbox" name="SectionNumber[]" value="<?=$row4['SectionNumber'];?>" id="SectionNumber[]"><?=$row4['SectionNumber'];?></label>
      <?php endwhile; ?>
   </p>
   <div class="form-inline">
   <table class="table table-striped">
      <thead>
         <tr class="table-text-center">
            <th scope="col"> Letter Grade</th>
            <th scope="col">Percent Toward Grade</th>
            <th scope="col">Avg Steps/Day</th>
            <th scope="col">Average Active Minutes/Week</th>
         </tr>
      </thead>
      <tbody>
         <?php
            while ($row = $result->fetch_assoc()) {
            $id = $row['id'];
            $letter = $row['letter'];
            $AssignmentID = $row['AssignmentID'];
            $percent = $row['percent'];
            $avgsteps = $row['avgsteps'];
            $avgweeklymin = $row['avgweeklymin'];
            $section = $row['section']; 
             ?>
         <input name="id[]" type="hidden" value="<?php echo "$id"; ?>"/>
         <input name="section[]" type="hidden" value="<?php echo "$section"; ?>"/>
         <input name="AssignmentID[]" type="hidden" value="<?php echo "$AssignmentID"; ?>"/>
         <tr class="table-text-center">
            <td>
               <div class="col-sm-10">
                  <input type="text" class="form-control" id="letter" name="letter[]" aria-describedby="letter" placeholder="Grade" value="<?php echo "$letter"; ?>"> 
               </div>
            </td>
            <td>
               <div class="col-sm-10">
                  <input type="text" class="form-control" id="percent" name="percent[]" aria-describedby="percent" placeholder="Percent" value="<?php echo "$percent"; ?>"> 
               </div>
            </td>
            <td>
               <div class="col-sm-10">
                  <input type="text" class="form-control" id="avgsteps" name="avgsteps[]" aria-describedby="points" placeholder="Average Steps" value="<?php echo "$avgsteps"; ?>"> 
               </div>
            </td>
            <td>
               <div class="col-sm-10">
                  <input type="text" class="form-control" id="avgweeklymin" name="avgweeklymin[]" aria-describedby="avgweeklymin" placeholder="Average Weekly Activity Minutes" value="<?php echo "$avgweeklymin"; ?>"> 
               </div>
            </td>
         </tr>
         <?php } ?>
      </tbody>
   </table>
   <input class="btn btn-lg btn-primary btn-block" type="submit" value="Save Changes">
</form>

PHP код:

$size = count( $_POST[ 'id' ] );
$numofsections = count( $_POST[ 'SectionNumber' ] );

$stmt = $connection->prepare( "INSERT INTO GradingScale SET letter=?,percent=?,avgsteps=?,avgweeklymin=?,section=?,AssignmentID=? ON DUPLICATE KEY UPDATE letter=?,percent=?,avgsteps=?,avgweeklymin=?,section=?,AssignmentID=?" );

for($x = 0; $x < $numofsections; $x++):

    $SectionNumber = array_fill(0, $size, $_POST['SectionNumber'][$x]);

$i = 0;
while ( $i < $size ) {
    // define each variable 
    $id = filter_var( $_POST[ 'id' ][ $i ], FILTER_SANITIZE_NUMBER_INT );
    $letter = filter_var( $_POST[ 'letter' ][ $i ], FILTER_SANITIZE_STRING );
    $percent = filter_var( $_POST[ 'percent' ][ $i ], FILTER_SANITIZE_NUMBER_INT );
    $avgsteps = filter_var( $_POST[ 'avgsteps' ][ $i ], FILTER_SANITIZE_NUMBER_INT );
    $avgweeklymin = filter_var( $_POST[ 'avgweeklymin' ][ $i ], FILTER_SANITIZE_NUMBER_INT );
    $AssignmentID = filter_var( $_POST[ 'AssignmentID' ][ $i ], FILTER_SANITIZE_NUMBER_INT );
    $SectionNumber = filter_var( $_POST[ 'SectionNumber' ][ $i ], FILTER_SANITIZE_STRING );
    echo $SectionNumber .  "  is SectionNumber<BR>"; 

    $stmt->bind_param( "siiisisiiisi", $letter,$percent, $avgsteps, $avgweeklymin, $SectionNumber, $AssignmentID, $letter,$percent, $avgsteps, $avgweeklymin, $SectionNumber, $AssignmentID);
    $stmt->execute();

    //$stmt2->bind_param( "iii", $PointsPossible, $SectionNumber, $AssignmentID );
    //$stmt2->execute();

    ++$i;
}
endfor;

Схема базы данных

CREATE TABLE `GradingScale` (
  `id` int(11) NOT NULL,
  `letter` enum('A','B','C','D','F') NOT NULL,
  `percent` smallint(4) NOT NULL,
  `avgsteps` smallint(6) NOT NULL,
  `avgweeklymin` smallint(4) NOT NULL,
  `section` varchar(8) NOT NULL,
  `AssignmentID` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Grading Scale';


INSERT INTO `GradingScale` (`id`, `letter`, `percent`, `avgsteps`, `avgweeklymin`, `section`, `AssignmentID`) VALUES
(1, 'A', 100, 10000, 100, '5011', 1),
(2, 'A', 90, 9500, 90, '5011', 1),
(3, 'B', 80, 9000, 80, '5011', 1),
(4, 'C', 70, 8500, 70, '5011', 1),
(5, 'D', 60, 8000, 60, '5011', 1),
(6, 'F', 50, 7500, 50, '5011', 1),
(7, 'F', 40, 7000, 40, '5011', 1),
(8, 'F', 30, 6500, 30, '5011', 1),
(9, 'F', 20, 6000, 20, '5011', 1),
(10, 'F', 10, 5500, 10, '5011', 1),
(11, 'F', 0, 5000, 0, '5011', 1),
(12, 'A', 100, 10000, 100, '5013', 1),
(13, 'A', 90, 9500, 90, '5013', 1),
(14, 'B', 80, 9000, 80, '5013', 1),
(15, 'C', 70, 8500, 70, '5013', 1),
(16, 'D', 60, 8000, 60, '5013', 1),
(17, 'F', 50, 7500, 50, '5013', 1),
(18, 'F', 40, 7000, 40, '5013', 1),
(19, 'F', 30, 6500, 30, '5013', 1),
(20, 'F', 20, 6000, 20, '5013', 1),
(21, 'F', 10, 5500, 10, '5013', 1),
(22, 'F', 0, 5000, 0, '5013', 1),
(23, 'A', 100, 10000, 100, '5099', 1),
(24, 'A', 90, 9500, 90, '5099', 1),
(25, 'B', 80, 9000, 80, '5099', 1),
(26, 'C', 70, 8500, 70, '5099', 1),
(27, 'D', 60, 8000, 60, '5099', 1),
(28, 'F', 50, 7500, 50, '5099', 1),
(29, 'F', 40, 7000, 40, '5099', 1),
(30, 'F', 30, 6500, 30, '5099', 1),
(31, 'F', 20, 6000, 20, '5099', 1),
(32, 'F', 10, 5500, 10, '5099', 1),
(33, 'F', 0, 5000, 0, '5099', 1);

--
-- Indexes for table `GradingScale`
--
ALTER TABLE `GradingScale`
  ADD UNIQUE KEY `id` (`id`,`letter`,`percent`);

-- AUTO_INCREMENT for table `GradingScale`
--
ALTER TABLE `GradingScale`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=34;
COMMIT;

Любая помощь будет принята с благодарностью !!!

Тим

1 Ответ

0 голосов
/ 05 мая 2018

Это назначение:

$SectionNumber = array_fill(0, $size, $_POST['SectionNumber'][$x]);

перезаписывается этим:

$SectionNumber = filter_var( $_POST[ 'SectionNumber' ][ $i ], FILTER_SANITIZE_STRING );

Я думаю, что вы хотите сделать, это:

$SectionNumbers = array_fill(0, $size, $_POST['SectionNumber'][$x]);
...
$SectionNumber = filter_var( $SectionNumbers[ $i ], FILTER_SANITIZE_STRING );

Обратите внимание на добавление массива $SectionNumbers для хранения значений.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...