简体   繁体   中英

How to update the database using a checkbox in a table column?

I am new to PHP and just began to learn JS as it is required at this phase of the project. I have a database named- asms table named - filtersms column named - filter_op . In this column of the table I have a checkbox for each row and my requirement is to enter 'yes' to the filter_op column once I check the checkbox and remains 'no' if not checked. I tried to do this using PHP itself but happens to be impossible to update the table on the click of the checkbox. As I am a beginner to JS can you please help me to get through this. This is how filtersms table looks like,

|id  |vendor  |alarm_name           |filter_op|       
|1   |HUAWEI  | communication fault |no       |
|2   |HUAWEI  | STP link fault      |no       |
|3   |ZTE     | Battery discharge   |no       |
|4   |ZTE     | AC power off        |no       |

Following is the PHP code I written so far to add a checkbox to each row and display the table.

<!-- Begin Page Content -->
<div class="container-fluid">

  <!-- Page Heading -->
  <h1 class="h2 mb-2 text-gray-800">Filter SMS</h1>

  <!-- DataTales Example -->
  <div class="card shadow mb-4">
    <div class="card-header py-3">
      <h4 class="m-0 font-weight-bold text-primary">Filtered SMS Summary</h4>
    </div>
    <div class="card-body">

    <?php
      //Table select query for database
      require('include/connection.php');

      $query1="SELECT* FROM  filtersms ";
      $result_set=mysqli_query($connection,$query1);


     // require('include/filtercheck.php');

    ?>

      <div class="table-responsive">
        <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
          <thead>
            <tr>
              <th>Vendor</th>
              <th>Alarm</th>
              <th>Filter Option</th>

            </tr>
          </thead>
          <tfoot>
            <tr>
              <th>Vendor</th>
              <th>Alarm</th>
              <th>Filter Option</th>
            </tr>
          </tfoot>
          <tbody>

          <?php
            while($row=mysqli_fetch_assoc($result_set))  {
           ?> 

              <tr>
                <td><?php echo $row["vendor"];  ?></td>
                <td><?php echo $row["alarm_name"];  ?></td>
                <td>
                    <form action="include/filtercheck.php" method="POST">
                        <div class="form-check">
                            <input type="checkbox" class="form-check-input" value="yes" name="filter_check" id="filter_check"/>
                            <label class="form-check-label" for="filter_check">Filter Alarm</label>
                        </div>
                    </form>
                </td>
              </tr>   

             <?php
              }
             ?>

You can use jQuery.post() for it.

For each row, use:

<tr>
  <td><?php echo $row["vendor"]; ?></td>
  <td><?php echo $row["alarm_name"]; ?></td>
  <td>
    <input type="checkbox" value="2" class="js-checkbox-filter" <?php echo ($row["filter_op"] == "yes" ? "checked" : NULL) ?> />
  </td>
</tr>

These checkbox are now identified by the js-checkbox-filter class, and you can use it to bind a jQuery.change() event handler on it.

var checks = $(".js-checkbox-filter")

checks.change(function() {
  $.post("filtercheck.php", {
    id: this.value,
    filtered: this.checked ? "yes" : "no"
  })
})

You'll have to change your filtercheck.php file too. It must receive an id and filtered ("yes"/"no") parameters through $_POST variable. Use them to update your database table.

You can try something like this if I understand your question correctly. That uses jQuery so you need to include the CDN script. That basically submits data via AJAX indicating the new filter options for the row checked or unchecked. It does that my posting an array as filter_op_post having index 0 = to true or false and index 1 equal to the id of the row in the database. You can process that in the filtercheck.php file, although I included a little snippet. Let me know if that works for you.

That AJAX response is in "data", so you can return whatever you want and process that as needed.

POST:

filter_op_post[] […] 0 true 1 2

RESPONSE:

["true","2"] eg

index.php page:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous">
</script>
<!-- Begin Page Content -->
<div class="container-fluid">
<!-- Page Heading -->
    <h1 class="h2 mb-2 text-gray-800">
        Filter SMS
    </h1>
<!-- DataTales Example -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h4 class="m-0 font-weight-bold text-primary">
                Filtered SMS Summary
            </h4>
        </div>
        <div class="card-body">
<?php
$Config = array(
    'DB_TYPE' => 'mysql',
    'DB_HOST' => '127.0.0.1',
    'DB_NAME' => 'alarmfilter',
    'DB_USER' => 'root',
    'DB_PASS' => 'root',
    'DB_PORT' => '3306',
    'DB_CHARSET' => 'utf8'
);
$options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING, PDO::ATTR_EMULATE_PREPARES => true );
try {
$database = new PDO($Config['DB_TYPE'] . ':host=' . $Config['DB_HOST'] . ';dbname=' . $Config['DB_NAME'] . ';port=' . $Config['DB_PORT'] . ';charset=' . $Config['DB_CHARSET'], $Config['DB_USER'], $Config['DB_PASS'], $options);
}

catch (PDOException $e) {

                // Echo custom message. Echo error code gives you some info.
                echo 'Database connection can not be estabilished. Please try again later.' . '<br>';
                echo 'Error code: ' . $e->getCode();

                // Stop application :(
                // No connection, reached limit connections etc. so no point to keep it running
                exit;
}

$query="SELECT* FROM filtersms ";
$parameters = [];
$stmt = $database->prepare($query);
$stmt->execute($parameters);
$result_set =  $stmt->fetchAll(PDO::FETCH_ASSOC);

?>
            <div class="table-responsive">
                <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th>Vendor</th>
                            <th>Alarm</th>
                            <th>Filter Option</th>
                        </tr>
                    </thead>
                    <tfoot> 
                    <tr>
                        <th>Vendor</th>
                        <th>Alarm</th>
                        <th>Filter Option</th>
                    </tr>
                    </tfoot> 
                    <tbody>
<?php
            foreach ($result_set as $row)  {
           ?>
                        <tr>
                            <td><?php echo $row["vendor"];  ?>
                            </td>
                            <td><?php echo $row["alarm_name"];  ?>
                            </td>
                            <td> 
                            <form>
                                <div class="form-check">
<?php $checked = ($row["filter_op"] == "true")?"checked":""; ?>
                                    <input 
<?php echo $checked;  ?>
                                    type="checkbox" class="form-check-input filter_check" id ="filter_op_id
<?php echo $row["id"];  ?>
                                    "/> 
                                    <input type="hidden" name="filter_op_post[]" value="<?php echo $row[" filter_op"]; ?>
                                    "/> 
                                    <input type="hidden" name="filter_op_post[]" value="<?php echo $row[" id"]; ?>
                                    "/> <label class="form-check-label" for="filter_check">Filter Alarm</label> 
                                </div>
                            </form>
                            </td>
                        </tr>
<?php
              }
             ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<style> table, table tr, table td {
    border:black 1px solid;
    border-collapse: collapse;
</style>
<script>
    $(".filter_check").on("click", function(e) {

        $(this).next().val($(this).prop("checked"));
        formdata = $(this).closest("form").serialize();

            $.ajax({

                type: "POST",
                url: 'include/filtercheck.php',
                dataType: "json",
                data: formdata,
                beforeSend: function(e) {
                    // $("#spinner").css("display", "block");
                },
            })
            .done(function(data, textStatus, jqXHR) {
                alert(data);
            })
            .fail(function( jqXHR, textStatus, errorThrown) {
            })
            .always(function(jqXHR, textStatus) {
                $("#spinner").css("display", "none");
            });
    });
</script>

include/filtercheck.php page:

<?php

$rowid = $_POST['filter_op_post'][1];
$filter_op_value = $_POST['filter_op_post'][0];
echo json_encode($_POST['filter_op_post']);


?>

You could use a form with a submit button.

    <form method="POST">
    <input type="checkbox" class="form-check-input" value="true" name="filter_check" id="filter_check"/>
    <label class="form-check-label" for="filter_check">
    <button type="submit" name"submit" value="Submit">Submit</button>
    </form>

With this you could update the database using the Post method

if(isset($_POST['submit']))
{
   /* update database here 
   /* your value of the checkbox is &_POST['filter_check']
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM