Assuming both the button listing and the form handling code chunks you posted are residing in the same file admin.php
, I believe it is always showing the 3rd (last) row in your table because the first fetch while
loop defines the variable $id
, which you then used directly later when processing the form.
Instead, to select an $id
value and pass it to the form handling code, you will need an additional <input>
tag that holds its value, and retrieve it from $_POST
in the form processing:
<?php
$sql = "SELECT id FROM mensproducts";
$result = mysqli_query($connection,$sql);
if(mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
// THIS final value of $id is what is mistakenly being passed to your SQL, whatever it holds at the end of the loop.
$id = $row['id'];
echo $id;
// Create an <input> with the $id -- this uses a hidden one
// Note: each listing is now its own separate <form>
// This does not matter for the HTML, though it might require changes to your CSS if it causes different visual appearance.
// Necessary so that the same input name can be used.
?>
<form action="admin.php" method="POST">
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="submit" name="submitid" value="Choose Id"/>
</form>
Then in your form processor, retrieve $_POST['id']
which the form now sends, and use that in your SQL.
if (isset($_POST['submitid'])) {
// Get your $id from the form post
$id =mysqli_real_escape_string($connection, $_POST["id"]);
$result = mysqli_query($connection,"SELECT * FROM mensproducts WHERE id = '$id'");
while($row = mysqli_fetch_assoc($result)){
echo "
<div class='id'> Id = ".$row['id']."</div>
<div class='name'>".htmlspecialchars($row['name'])."</div>
<div class='desc'>".htmlspecialchars($row['description'])."</div>
<div class='price'>£".htmlspecialchars($row['price'])."</div>
</div>";
}
}
?>
// I closed the </form> tag earlier.
Note: I am adding mysqli_real_escape_string()
here, which is the bare minimum you must do to protect your code against database tampering via SQL injection. A better method is to use prepare()/bind_param()/execue()
in MySQLi. See How can I prevent SQL injection in PHP for details and examples.
Note 2: I have removed the extra spaces around html attributes, turning <input name = 'submitid'>
into <input name='submitid'>
. While most browsers today won't care, it is accepted practice not to put spaces around the =
in attributes
Note 3: I added htmlspecialchars()
around the database values printed into your HTML. That correctly encodes any characters like < > &
which might break the markup. An important habit to be in.