Huckleberry Finn
Huckleberry Finn

Reputation: 159

PHP While loop in Table in Form

I'm trying to create a Table where you can 'Sign Off' items populating it. Currently the table looks to be populated fine, however when you go to 'Sign Off' an item - it will only act on the latest mysql row ['directory'] as well as the latest text field accompanying it.

When I say 'Sign Off' I mean to insert someone's initials into the mysql table row associated with that item. I first of course need to get the POST submission handled correctly.

That probably wasn't articulated perfectly, so please take a look at my current code;

echo "<form action='signoff.php' method='post' id='signoffform' style='display:inline;'>";
echo "<p3><table id='myTable3' class='tablesorter'> 
<thead> 
<tr>
    <th>To Delete</th>
    <th>Directory</th> 
    <th>Space Used</th>
</tr> 
</thead>";

while($row = mysqli_fetch_array($result))
{

echo "<tr>";
echo "<td><input type='text' name='signoff' id='signoff' form='signoffform' /><button>Sign Off</button> Signed Off By:" . $row['signoff'] . "</td>";
echo "<td><input type='text' name='dir' id='dir' form='signoffform' value='" . $row['directory'] . "' readonly /></td>";
echo "<td>" . $row['used'] . "</td>";
echo "</tr>";

}
echo "</table></p3>";
echo "</form>";

signoff.php

<?php
echo $_POST["signoff"];
echo "<br />";
echo $_POST["dir"];
?>

Please feel free to request more info

Upvotes: 2

Views: 1471

Answers (1)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

... when you go to 'Sign Off' an item - it will only act on the latest mysql row ['directory'] as well as the latest text field accompanying it.

The problem is because of your name attributes, name='signoff' and name=dir. When you loop through the result set, the name attribute value gets overwritten in each iteration. Hence whatever button you click, you'll always get the last row values.

So the solution would be like this:

Change your while loop in the following way,

// your code

while($row = mysqli_fetch_array($result)){
    echo "<tr>";
    echo "<td><input type='text' name='signoff[".$row['directory']."]' id='signoff' form='signoffform' /><button>Sign Off</button> Signed Off By:" . $row['signoff'] . "</td>";
    echo "<td><input type='text' name='dir[".$row['directory']."]' id='dir' form='signoffform' value='" . $row['directory'] . "' readonly /></td>";
    echo "<td>" . $row['used'] . "</td>";
    echo "</tr>";
}

// your code

And on signoff.php page, process your form in the following way,

foreach($_POST['dir'] as $dir){
    if(!empty($_POST['signoff'][$dir])){
        $signoff = $_POST['signoff'][$dir];

        // That how you can get $dir and the corresponing $signoff value

    }
}

Sidenote: If you want to see the entire $_POST array structure, do var_dump($_POST); on signoff.php page.

Upvotes: 1

Related Questions