Selom
Selom

Reputation: 735

Return the exact ID using fetch_assoc

I have a small problem in my code. I'm using fetch_assoc to get data from database and I need to get the ID number of each of returned values. the issue is that my code only return the ID number of the last data. Here's my code:

<form method="post" action="action.php">
  
  <select name="album" style="border:1px solid #CCC; font-size:11px; padding:1px">
      
       <?php

          $sql = "SELECT * FROM table";
          $stmt = $dbh -> prepare($sql);
          $stmt -> execute();
          
          while($row = $stmt -> fetch(PDO::FETCH_ASSOC))
          {
 
            $album_ID = $row['album_ID'];
            $value = $row['album_name'];         
            print "<option value ='". $value ."'>". $value. "</option>";


          }

       ?>
  
  </select>
  <input type="hidden" name="album_ID" value="<?php print $album_ID?>"/>
</form>

I would like the hidden input type holds the selected album id, but it always holds the album id of the last data.

Upvotes: 0

Views: 549

Answers (2)

Gaurav Sharma
Gaurav Sharma

Reputation: 2848

The hidden field will always contain the ID of the last row fetched.

I would like the hidden input type holds the selected album id, but it always holds the album id of the last data.

To achieve this you will have to set the value of hidden field upon the change event of select box using JavaScript.

Upvotes: 0

Lizard
Lizard

Reputation: 45032

Your best bet would be to place the id in the value od the option

....
while($row = $stmt -> fetch(PDO::FETCH_ASSOC))
{

    $album_ID = $row['album_ID'];
    $value = $row['album_name'];         
    print "<option value ='". $album_ID ."'>". $value. "</option>";


}

....

Then on the submission script (admin.php) the POST variable album will contain the ID, there is no need for the hidden input

Upvotes: 0

Related Questions