How can I update any row rather than only the top row with the update button on each side in PHP and AJAX

3011 views javascript

just starting out so gonna sound like a noob question but how can I use the update button to update individual rows rather than only the top row. Whenever I use the update button, the request only goes through if it was the top row.

This is the code for the index.php

    <script src=""></script>
    <h3>UPDATE DATA</h3>

    $run = 0;
    $conn = new mysqli('localhost', '', '', '');
    $sql = "SELECT * FROM moderator";
    $result = $conn->query($sql);
    while ( $row=mysqli_fetch_assoc($result)) {
        $run = $run + 1;

       ID<input type="text" id="id" value="<?php echo $row['id']; ?>">;
       Moderator<input type="text" id="mod" value="<?php echo $row['name']; ?>">;         
       Category<input type="text" id="ctgr" value="<?php echo $row['category']; ?>">;

       <button type="submit" id="update" rel="<?php echo $run; ?>">UPDATE</button>

                var name=$("#mod").val();
                var ctgr=$("#ctgr").val();
                var id=$("#id").val();

This is the code for the update.php


$conn = new mysqli('localhost', '', '', '');
$sql="UPDATE moderator set name='$name', category='$ctgr' where id='$id'";
    echo "DATA updated";

You can probably see I'm trying to create an individual variable for each row but I can't figure it out. Sorry, code's very messy too.

I've removed datebase information but the rows display when credentials are inserted.

answered question

Each of your form inputs are going to be sharing the same ID which is incorrect. Each element should have their own ID. The best way to handle this is to give each input their own unique ID and then pass the entire form request via your AJAX. Then in your PHP you can loop over the values for your update statement.

2 Answers


You need to change your logic to inputs have unique ID and then use the value properly.

posted this

All your rows input elements have same id attribute

Like id of first rows elements are like id, mod, ctgr

Also id of second rows elements are id, mod ctgr

Jquery find first element, if multiple elements of same id there

You can make unique id by apppending a uniqe thing like row number or id itself

posted this

Have an answer?


Please login first before posting an answer.