tags:

views:

30

answers:

2

Hi, I have a small problem in my code and I need your help. Well Im 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. Please help.

+1  A: 

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

Lizard
+1  A: 

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. Please help.

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

Gaurav Sharma
This would work but is overkill, would be best to just use the option value to the ID and forget the hidden input altogether.
Lizard
@lizard, yes it will but 'Selom' wanted this. I didn't know what is his ultimate goal is? Maybe he needed to do some javascript based calculation depending upon the value selected in the option. That's why I answered in the straight way as he asked.
Gaurav Sharma