The Codesee The Codesee - 5 months ago 12
PHP Question

Only first ID from table is displayed

I have a database table as followed:

enter image description here

Using the code below, I display the

text
column in a while loop:

$stmt = $con->query("SELECT * FROM test");
if($stmt->rowCount() > 0) {
$replyid = $row['ID'];
while($row = $stmt->fetch()) {
echo'
'.$row['text'].'
<form method="post">
<input name="testing" type="submit">
</form>
';
}
}


When the user clicks the submit button, the code below is supposed to display the
ID
corresponding to the column
text
. For example:


  • If the submit button next to 'hello' was clicked, the number 2 should display.

  • If the submit button next to 'adios' was clicked, the number 4 should display.

    if(isset($_POST['testing'])) {
    echo $replyid;
    }



My problem is that only the
ID
from the first row in the table is displaying. If the user clicks the submit button next to 'bonjour', the number 1 will display (instead of 3!)

Answer

You must add hidden field to form with your value:

echo'
     '.$row['text'].'
     <form method="post">
     <input name="replyid" type="hidden" value="'.$row['ID'].'">
     <input name="testing" type="submit">
     </form>
     ';

and then display that value from form

if(isset($_POST['testing'])) {
  echo $_POST['replyid'];
}
Comments