Use onoffswitch-checkbox to update table field in php

  1. Create a table in your database with the following fields: id (primary key), name, email, status.
  2. Create a PHP script that retrieves the data from the table and displays it in an HTML table.
  3. Create a page and name it index.php 



 
 index.php
<?php
// Assuming you have a database connection established
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Function to fetch data from the database
function fetchData() {
    global $conn;
    $sql = "SELECT * FROM users";
    $result = $conn->query($sql);
    $data = array();
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
    }
    return $data;
}

// Fetch data from the database
$data = fetchData();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bootstrap Switch Example</title>
    <!-- Include Bootstrap CSS and JS -->
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.bundle.min.js"></script>
    <!-- Include Bootstrap Switch CSS and JS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.4/css/bootstrap3/bootstrap-switch.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.4/js/bootstrap-switch.min.js"></script>
</head>
<body>

<div class="container mt-5">
    <h2>Users Table</h2>
    <table class="table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($data as $row) : ?>
                <tr>
                    <td><?= $row['id'] ?></td>
                    <td><?= $row['name'] ?></td>
                    <td><?= $row['email'] ?></td>
                    <td>
                        <input type="checkbox" class="status-switch" data-id="<?= $row['id'] ?>" <?= $row['status'] == 1 ? 'checked' : '' ?>>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<script>
    // Initialize Bootstrap Switch
    $('.status-switch').bootstrapSwitch({
        size: 'small',
        onSwitchChange: function (event, state) {
            var id = $(this).data('id');
            var status = state ? 1 : 0;

            // Use AJAX to update the status in the database
            $.ajax({
                url: 'update_status.php',
                method: 'POST',
                data: {id: id, status: status},
                success: function (response) {
                    // Handle success if needed
                },
                error: function (error) {
                    // Handle error if needed
                    console.log(error);
                }
            });
        }
    });
</script>

</body>
</html>

 

Add JavaScript code to handle the change event of the onoffswitch-checkbox and update the active field using AJAX. This code given below is included in the same page.

 

<script>
    // Initialize Bootstrap Switch
    $('.status-switch').bootstrapSwitch({
        size: 'small',
        onSwitchChange: function (event, state) {
            var id = $(this).data('id');
            var status = state ? 1 : 0;

            // Use AJAX to update the status in the database
            $.ajax({
                url: 'update.php',
                method: 'POST',
                data: {id: id, status: status},
                success: function (response) {
                    // Handle success if needed
                },
                error: function (error) {
                    // Handle error if needed
                    console.log(error);
                }
            });
        }
    });
</script>

 

Create a PHP script called update.php that receives the ID and status values, updates the table, and returns a response.  Test your code by opening the PHP script that displays the table in your browser, toggling the onoffswitch-checkbox, and checking that the status field



 

<?php
// Assuming you have a database connection established
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Function to update the 'active' field based on checkbox state
function updateStatus($id, $status) {
    global $conn;
    $sql = "UPDATE users SET status = $status WHERE id = $id";
    $conn->query($sql);
}

// Handle checkbox state change using AJAX
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id']) && isset($_POST['status'])) {
    $id = $_POST['id'];
    $status = $_POST['status'];
    updateStatus($id, $status);
    exit();
}

?>


Make sure to replace "servername," "username," "password," and "database"  with your actual database information. Also, adjust the paths for Bootstrap and Bootstrap Switch libraries as needed.