0

I've created a simple query of retrieving records from my database and passing it to a html. I want to add an edit/view button for each row so after some research, I ended up with this:

$query = mysqli_query($con, "SELECT * FROM mytable") or die(mysqli_error($con));
if(mysqli_num_rows($query) > 0) {
    while($row = mysqli_fetch_array($query)) {
        echo "<tr><td>".$row['pId']."</td>";
        echo "<td>".$row['data1']."</td>";
        echo "<td>".$row['data2']."</td>";
        echo "<td><form action='detailform.php' method='POST'><input type='hidden' name='tempId' value='".$row["pId"]."'/><input type='submit' name='submit-btn' value='View/Update Details' /><form></td>";
    }
}

This works fine for 1 record. But if I have 2 or more, the latest record is always retrieved regardless of which record you selected. For example, if you have 5 records and you select any record, the 5th record will always be selected so I am unable to update the previous records. Why is this is happening? Am I missing something?

Not sure if this helps my case but here's my the basic logic of my detailform.php:

if(isset($_POST["tempId"]){ 
     //pass data using post then update. Here's where I keep getting only the latest record regardless of selected record from previous page
} else { //add data }

2 Answers 2

4

Close the form:

echo "<td><form action='detailform.php' method='POST'><input type='hidden' name='tempId' value='".$row["pId"]."'/><input type='submit' name='submit-btn' value='View/Update Details' /></form></td></tr>";

The first one is sent correctly because it is the closest to the submit button, the rest will be closer to the last submit button

Sign up to request clarification or add additional context in comments.

1 Comment

Well doh *facepalms. I've been staring at code for 8 hours straight so I totally missed that one. Apparently, that's the only thing I'm missing. Thanks a lot!
1

try this

 while($row = mysql_fetch_assoc($query)) {
        echo "<tr><td>".$row['pId']."</td>";
        echo "<td>".$row['data1']."</td>";
        echo "<td>".$row['data2']."</td>";
        echo "<td><form action='detailform.php' method='POST'><input type='hidden' name='tempId' value='".$row["pId"]."'/><input type='submit' name='submit-btn' value='View/Update Details' /></form></td></tr>";
    }

3 Comments

Thanks. I did miss that </tr> at the end but it's still the same issue.
@@user1597438 ans has been updated... hope it ll solve your prob.. :)
Yep it does. I just missed the closing tag of form aside from the row. Thanks! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.