Ellen
Ellen

Reputation: 3

How do I get ID of a button selected?

Hi I have lots of items that are displayed. It's in a while loop in which there name,instructions etc is displayed as well as a button

So, each item has it's own image,instructions etc.

I'm wondering how can I get the ID of that item that the button was selected?

Basically, i want to get the ID of that recipe and insert it into the database

Upvotes: 0

Views: 501

Answers (2)

Devendra Choudhary
Devendra Choudhary

Reputation: 32

## Use this php code its working according your database ##
<?php 

if(issset($_POST['submit'])){
$ID = $_POST['ID'];
/*your user id here i can use static for example*/
$User='1';

 $query = $db->prepare('INSERT INTO User (User, ID) VALUES (:User, :ID)');
    $stmt->execute(array(
        ':User' =>$User,
        ':ID' =>$ID
));
}

    <?php
       while ($dbRow=$dbQuery->fetch(PDO::FETCH_ASSOC)) 
        {
?>
           <h4><?php echo $dbRow["Name"]; ?></h4><img src="<?php echo $dbRow['Picture']; ?>" width='150' height='150' /><br> <?php echo $dbRow["Instructions"]; ?><br><form method='POST'>
<input type="hidden" name="RecipeID" value="<?php echo $dbRow['RecipeID']; ?>">
<input type='submit' name='submit' value= "Recipe_<?php echo $dbRow['RecipeID']; ?>" class='button-recipe'>
</form><!--close the form-->
<?php
            }



     ?>

Upvotes: 0

infinitezero
infinitezero

Reputation: 2078

You can use hidden fields to send additional information with your form. This basically works like any other input field, except, that the user does not see it in the front end.

<form method="GET" action="target.php">
  <input type="hidden" name="myHiddenField" value="myHiddenValue" />
  <input type="submit" name="submitForm" value="submit" />
</form>

And to read the data

<?php
if( isset($_GET['myHiddenField']) ){
  echo 'Hidden field value: '.$_GET['myHiddenField'];
}
?>

You can also use this with POST instead of GET

edit: In your case, just put the hidden field in your loop:

 while ($dbRow=$dbQuery->fetch(PDO::FETCH_ASSOC)) 
 {
     ?>
     <?= $dbRow['Name'] ?>
    <br/>
    <img src="<?= $dbRow['Picture'] ?>" width="150" height="150"/>
    <br/>
    <?= $dbRow['Instructions"'] ?>
    <form method="POST">
        <input type="submit" name="submit" value="Complete" class="button-recipe"/>
        <br>
        <br>
        <!--<h4><?= $dbRow["RecipeID"] ?> I put this in even though i dont want it to be displayed, but I'm not sure how else i can get the ID? -->
       <input type="hidden" name="recipeID" value="<?= $dbRow['RecipeID'];" />
        <?php 
        }

You can then get the recipe ID with $_POST['recipeID'], once you clicked submit.

Upvotes: 2

Related Questions