Show individual row information within a bootstrap modal upon clicking the edit button

As a beginner in programming, I am attempting to use bootstrap modal to showcase row data from a mysql table within the modal window.

Following the advice found on stackoverflow regarding "Pull information from mysql table to bootstrap modal to edit" didn't quite work for me. I couldn't get the specific row with the $row['SFID'] to display.

Even though I can retrieve data from the table, whenever I click the edit button in front of any row, it consistently shows the ID of the last row and fails to populate the input box in the modal for editing the data.

This is where I'm stuck at now. Any assistance would be greatly appreciated.

<table class="table table-bordered" width="100%">
    <thead>
        <tr>
            <th>SFID</th>
            <th>Company</th>
            <th>Product</th>
            <th>Product Line</th>
            <th>Dealer Class</th>
            <th>Status</th>
        </tr>
    </thead>
    <?php
        $query = "SELECT * FROM tblcustomer";
        $stmt = $db->prepare($query);
        $stmt->execute();

        foreach ($stmt as $row): ?>
            <tr>
    <?php $rowID = $row['SFID']; ?>

                <td><?php echo $row['SFID']; ?></td>
                <td><?php echo $row['CompanyName']; ?></td>
                <td><?php echo $row['Product']; ?></td>
                <td><?php echo $row['ProductLine']; ?></td>
                <td><?php echo $row['DealerClass']; ?></td>
                <td><?php echo $row['RequestStatus']; ?></td>
                ...

...
<div id="editModal" class="modal hide fade in" style="display: none; ">
 <div class="modal-header">
    <a class="close" data-dismiss="modal">×</a>
    <h3>Edit Customer Details</h3>
</div>
 <div>
   <form class="contact">
     <fieldset>
       <div class="modal-body">
        <ul class="nav nav-list">
           <li class="nav-header">SFID</li>
           <li><input class="input-xlarge" type="text" name="mysfid" id="mysfid"></li>
         </ul> 
      </div>
    </fieldset>
  </form>
 </div>
 <div class="modal-footer">
    <button class="btn btn-success" id="submit">Approved</button>
      <a href="#" class="btn" data-dismiss="modal">Close</a>
 </div>
</div>

...
  <script>
    $(document).ready(function(){
    $('a.edit').click(function(){
    var sfid = $(this).data('sfid');
    var company = $(this).data('company');
    var dealerclass = $(this).data('dealerclass');    

    $('#mysfid').val(sfid);
    $('#mycompany').val(company);
    $('#mydealerclass').val(dealerclass);
    });

    });
    </script>

Your assistance is invaluable. Thank you!

Answer №1

<table class="custom-table" width="100%">
    <thead>
        <tr>
            <th>ID</th>
            <th>Company Name</th>
            <th>Product Type</th>
            <th>Product Line Class</th>
            <th>Client Category</th>
            <th>Current Status</th>
        </tr>
    </thead>
    <?php
        $query = "SELECT * FROM customersTable";
        $result = mysqli_query($connection, $query);
        $counter=1;
        while($row = mysqli_fetch_assoc($result))
        {
    ?>
            <tr>
    <?php $idValue = $row['ID']; ?>

                <td><?php echo $row['ID']; ?></td>
                <td><?php echo $row['CompanyName']; ?></td>
                <td><?php echo $row['ProductType']; ?></td>
                <td><?php echo $row['ProductLineClass']; ?></td>
                <td><?php echo $row['ClientCategory']; ?></td>
                <td><?php echo $row['StatusCode']; ?></td>
                <td style="text-align: center">
                    <div class="btn-section">
                        <div class="btn-group">
                            <a class="btn btn-danger" href="#deleteModal"  data-toggle="modal"><i class="icon-trash icon-white"></i> Delete</a>

                            <a class="btn edit-btn" href="#editDetails<?php echo$counter?>" data-id='"<?php echo $row['ID'];?>"' data-toggle="modal">Edit</a>
                            <!--Your Edit Modal Content-->
                            <div id="editDetails<?php echo $counter; ?>" class="modal hide fade in" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                             <div class="modal-header">
                                <a class="close" data-dismiss="modal">×</a>
                                <h3>Edit Customer Details</h3>
                            </div>
                             <div>
                            <form class="contact-form">
                               <fieldset>
                                <div class="modal-body">
                                    <?php echo $row['ID']; ?> 
                                    <ul class="nav nav-list">
                                    <li class="nav-header">ID</li>
                                    <li><input class="input-field" type="text" name="myID" id="myID"></li>
                                    <!--<li class="nav-header">Company Name</li>
                                    <li><input class="input-field" value="" type="text" name="myCompanyName"></li>
                                    <li class="nav-header">Client Category</li>
                                    <li><input class="input-field" value="" type="text" name="myClientCategory"></li> -->
                                    </ul> 
                                 </div>
                                </fieldset>
                            </form>
                             </div>
                             <div class="modal-footer">
                                <button class="btn btn-success" id="submitEditedData">Save Changes</button>
                                  <a href="#" class="btn close-btn" data-dismiss="modal">Close</a>
                             </div>
                            </div>

                             </div>
                    </div>
                </td>
             </tr>
     <?php $counter++; } ?>
 </table>

Answer №2

Increment the variable $i by 1 at the beginning of each iteration in the for loop to access individual records.

Your Form

<a class='btn update' href='#editModal<?php echo $i;?>' data-sfid='".$row['SFID']."' role='button' data-toggle='modal'>Edit</a>

Modal Window

<div id="editModal<?php echo $i;?>" class="modal hide fade in" style="display: none; ">

Answer №3

The reason for this behavior is that the edit modal is populated with the $row data, which is only available after reaching the last item.

If you need data for a particular row, consider creating a JavaScript object or array to retrieve the information using the "data-rfid" parameter in the "Edit" link. Another option is to fetch the row through Ajax requests.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Addressing the Cross Domain Issue when Implementing DHIS 2 API with jQuery

Today, I spent hours trying to authenticate my javascript application with the DHIS 2 API using Jquery. According to the API documentation (https://www.dhis2.org/doc/snapshot/en/user/html/ch32s02.html), base 64 authentication is required. However, my attem ...

Incorporating a JavaScript code into my SharePoint master page to automatically deselect a checkbox resulted in updating the page title

I've integrated the following JavaScript code into my SharePoint master page: <script type="text/javascript> function DefaultUploadOverwriteOff() { if (document.title== "Upload a document") { var input=document.querySelectorAll("input"); ...

Retrieving the initial array element within a foreach loop

I am just starting with ajax concepts... When I post data using ajax, only the first array from the foreach loop gets posted. Here is the code snippet: <tbody id="presentor"> <?php if(!empty($data)):?> <?php $counter = '0'; for ...

Performing subtraction operation on a selected floating-point value from a database using PHP

I am facing an issue with my code where I need to subtract a float value selected from the database and update the subtracted values in the database table. Below is my code snippet: $AmountGiven = $_POST['AmountGiven']; $conn = mysqli_connect("l ...

Showing the values of selected checkboxes in a select dropdown - here's how!

Link to the jsfiddle : https://jsfiddle.net/a1gsgh11/9/ The JavaScript code seems to not be working on the js fiddle platform. My main concern is that I would like the selected checkbox values to display immediately without needing to submit any buttons. ...

What is the process for submitting a form on consecutive URLs?

I have a form that requires input for settings and includes two buttons: one to save the form and another to both save and execute the settings. <form method="post" action="/settings/{{id}}/save"> <!-- input fields --> ...

ajax-jquery request declined

I have a jquery-ajax function that is being called multiple times with different IP addresses each time. This function makes a call to an action in the mvc4 controller responsible for executing a ping and returning the results. After analyzing the request ...

The PDO MySQL error HY093 was thrown due to an incorrect number of parameters being passed

Encountering an HY093 (Parameter count mismatch) SQLSTATE error on a query that seems to have the correct number of parameters. Here is a complete PHP script to reproduce the issue. (Remember to update the database credentials.) The SELECT statement conta ...

When completing a form submission, make sure to eliminate the %5B%5D from the

Whenever I submit a form with multiple checkboxes that share the same name, the resulting URL format is as follows: www.example.com/search.php?myvalue%5B%5D=value1&myvalue%5B%5D=value2 Is there a method to eliminate the %5B%5D in the URL and make it m ...

Show results from mySQL that are alike

Is there a way to generate a query that provides similar words if an exact match cannot be found? For example, when the query is attempting to match "mstke" and comes up empty in the database, the results should include related words like "mistake", "misst ...

Modifying the input field's name attribute while utilizing multiple datasets in typeahead.js

I am currently utilizing typeahead.js with multiple datasets, following the guidance provided here. I have chosen not to employ Bloodhound in my implementation, resulting in some differences in my code structure, outlined below: $('#search .typeahead ...

Can setting PHP error_reporting(0) impact both error logging and display, or just how errors are shown?

Can using error_reporting(0); impact error logging to a file, or does it simply hide errors from being displayed on screen? Appreciate your input. ...

Unleashing the Power of Ajax: Exploring

Currently, I have implemented an onkey event with ajax to facilitate the search functionality for customer-typed input. As a result, I am able to retrieve a list of strings based on what the customer has typed. However, I face a challenge when it comes t ...

Confirming whether the digit entered in jQuery is a number

My website has a user input field where numbers are expected to be entered. I wanted to find a convenient way to validate the input using jQuery. After some research, I discovered jQuery's built-in function called isDigit. This handy function allows ...

Unable to establish the default timezone in PHP

After updating the date.timezone setting in my php.ini file and restarting the php5-fpm process, I noticed that the phpinfo() script still displayed the incorrect timezone: America/New_York. date.timezone = "UTC" Despite confirming that the correct ini f ...

Setting the timer: setTimeout function

As a beginner in jQuery, I am looking for the most efficient way to create a slideshow that automatically changes pictures and button statuses at set intervals. However, I want the auto image transitions to pause when a user clicks on any of the image butt ...

Trouble accessing contacts on LinkedIn

When attempting to retrieve the LinkedIn connections for a logged-in user, I used the following API Request: However, I encountered an error message: { "errorCode": 0, "message": "Access to connections denied", "requestId": "OFP0JOLOHO", "status" ...

The tabs functionality is broken due to an upgrade in jQuery and jQuery UI

I recently upgraded my website to use the latest versions of jQuery and jQuery UI, but I'm facing some unexpected issues with the Tabs widget. Previously, everything was working fine with jQuery 1.5.1 and jQuery UI 1.8.4. After upgrading to jQuery 1. ...

Is it possible to transform multiple input values into a JSON array using PHP?

I am working on a task to convert various input values into a JSON array using PHP. Here is the form structure: <input name="title[]"> <input name="description[]"> <input name="total[]"> This is the desired ...

Tips for accessing a website and logging in to extract important data for scraping purposes

Currently facing an issue with scraping data from a website that requires logging in. I've been attempting to use the node request package for the login process, but so far have been unsuccessful. The code snippet I'm currently using is: var j = ...