0

I want to display checked checkbox which are stored as values in a mysql database.

For now the table stores the value of the checkbox being checked in the database. The header and first column are fetched from three different tables in the database. While the values of the checked check-boxes gets saved in a same table.

Here's the code for inserting the data.

$active = "CourseReport";
require_once 'pages/header.php';
require_once './functions/schema-functions.php';
require_once './functions/report-functions.php';
$course = Schema::getCourseReport();
$objective = Schema::getObjective();
$goals = Schema::getGoals();
$mainobj = Schema::getMainObjectives();
$subobj = Schema::getSubObjectives();
 ?>

<form id="addReport" action ='./functions/report-functions.php' method="post">

<table id="table1" class="table table-hover">

    <thead>
    <?php
    echo '<tr><th>Goals</th>';
    for ($i = 0; $i < count($course); $i++) {
        echo '<th id = "rotate1">'. $course[$i]->commonName . '</th>';            
    }
    echo '</tr>';   
    ?>
    </thead>
        <tbody>

    <?php
    for ($y = 0; $y < count($goals); $y++) {           
        echo '<tr class="clickable"><th class="toggle">Goal#'.$goals[$y]['GoalId'].':'." " .' '.$goals[$y]['Goals'].'</th>

        </tr>';           
   ?>

    <?php
    for( $z = 0; $z < count($mainobj); $z++){
  if($mainobj[$z]['GoalId'] == $goals[$y]['GoalId']) {
        echo '<tr class="expander"><th class=row-header>Objective#'.$mainobj[$z]['MainObjId'].':'." ".' '.$mainobj[$z]['MainObjectives'].'</th>

    </tr>';
     ?>

    <?php

    for ($j = 0; $j< count($subobj); $j++) {
       if($mainobj[$z]['MainObjId'] == $subobj[$j]['MainObjId']){
       echo '<tr class="expander"><td class=row-header>'.$subobj[$j]['SubObjId'].' ) '.$subobj[$j]['SubObjectives'].' </td>';

   for ($x = 0; $x < count($course); $x++) {
      echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
        }
        echo '</tr>';
    }
   }
  }
 }
}       
    ?>       
        </tbody>       
</table>
<button class="button" name= "submit" value= "Submit">Submit</button>

</form>

report-functions.php

if( isset( $_POST['submit'], $_POST['check'] ) ){
    try{
      require_once 'db-connect.php';
        $conn = DatabaseConnection::getConnection();
       $sql= " insert into `Report`  (`ColRow`) values (:value) ";
        $stmt = $conn->prepare( $sql );
       if( $stmt ){
         $conn->beginTransaction();
           foreach( $_POST['check'] as $index => $value ) {
               $result = $stmt->execute( [ ':value' => $value ] );
                if( !$result ) {
                   echo '
        <script>
           alert("Error, please try submitting again. Error code 1");
           window.history.back();
        </script>';
                }
            }
            $conn->commit();
          echo '<script>
            alert("Report was submitted successfully.");
            window.location = ".../";
        </script>';
      }
    } catch( Exception $e ){
       $conn->rollback();
        exit( $e->getMessage() );
    }

I expect that once I submit the table, the table should load the same table with the checked checkboxes. I should be able to make the changes and submit the table over and over again.

Please comment if I need to provide any additional information.

6
  • When you are about to load the page, do a select on the database. Then when you print your <input> element, add an if statement. If the value in the database is checked, add this to the <input> element: checked="checked". It will therefore be checked, based on the database value. Commented Jun 28, 2019 at 16:41
  • Thanks for your response. The database actually saves the row and the column number of the checked box. Should I add a auto column in the database which gets auto updated with each database entry? Or can you give an example of the code on how should I do it? Commented Jun 28, 2019 at 16:53
  • When your user presses submit, you save the value of $_POST['check'] into the ColRow item in the database. The reverse is also possible. Do a select on the database. If the value for ColRow equals the value you are about to print to the html page , then add the checked code on the input element. To go deeper in the explanation, you would have to add a database sample and html output sample to the question Commented Jun 28, 2019 at 18:34
  • I've added a picture of expected output. The header and the first column are like two different tables in the database. THe output gets saved as the id of the column and row the checked checkbox is located. For example if you select the very first checkbox, it will be saved like c1-o1.1 Commented Jun 28, 2019 at 18:59
  • Couple points: you do not need to close a PHP section (?>) to just open a new one on the next line (<?php). Open and close once. Another, to read your code, I put it in an editor and did the indentation again. Helped a lot. Still looking... Commented Jun 28, 2019 at 19:12

1 Answer 1

1

When you display your page (in your first section of code), at some point you do this:

echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";

The value is set to:

value=c"c.$course[$x]->courseId."-o".$subobj[$j]['SubObjId']";

This value is where you get the checked or not value you mentioned in the comments (like c1-o1.1).

Right. So before you do that echo, add a new if condition.

$value = "c$course[$x]->courseId" . "-o$subobj[$j]['SubObjId']";
if (verify_checked($value)) {
    $checked_code = "checked=\"checked\"";
}
else {
    $checked_code = "";
}
echo "<td><input name='check[]' type=checkbox value=$value id=checked $checked_code ></td>";

The verify_checked(value) function does (from what I understand of your database, you keep the "grid location" of checked elements):

function verify_checked($value)
{
    // Connect to the database if needed
    // Perform: SELECT count($value) FROM Report
    // If the result is >0, return TRUE
    // Else return FALSE
}
  • The idea here is to query the database every time your are about to echo the <input> element.
  • Note for concatenating text, I find it more legible to put spaces around the . to clearly split what is part of the text and what is the concatenation dot.
  • As mentioned previously, indentation is critical for understanding of the different contexts. Until I indented your code, I had not realized how the different loops worked in relation to the others.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.