selected option issue

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tito85
Forum Contributor
Posts: 104
Joined: Sat Mar 13, 2010 11:26 am

selected option issue

Post by tito85 »

Hi everyone,

I am using the below code in an edit page of movie information so in the genre field it displayed as selected the genres in the database.

My problem is that only one genre is showed as selected although the movie has more than 1 genre in the database.

Any idea why?

Code: Select all

<?php
 $select = "SELECT * FROM genres WHERE MovieID = '$id'";
          $result = mysql_query($select);
		  $genreid = mysql_result($result, 0, 'GenreTypeID');
?>
<?php
  $query = "SELECT * FROM genretypes ORDER BY Genre ASC";
  $result2 = mysql_query($query);
  while ($genre = mysql_fetch_array($result2)) {
      $selected = "";
      if ($genreid == $genre['GenreTypeID']) {
          $selected = "selected=\"selected\"";
      }
      echo "<option $selected value=\"" . $genre['GenreTypeID'] . "\">" . $genre['Genre'] . "</option>";
  }
?>
Thanks!!!
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: selected option issue

Post by AbraCadaver »

I'm making some assumptions on your tables, but you need to get all genres for the movie, you were only getting one. Then see if the current genre is in that list. Something like this:

Code: Select all

$select = "SELECT * FROM genres WHERE MovieID = '$id'";
$result = mysql_query($select);
while ($row = mysql_fetch_array($result)) {
	$movie_genres[] = $row['GenreTypeID'];
}

$query = "SELECT * FROM genretypes ORDER BY Genre ASC";
$result2 = mysql_query($query);
while ($genre = mysql_fetch_array($result2)) {
	$selected = "";
	if (in_array($genre['GenreTypeID'], $movie_genres)) {
		$selected = "selected=\"selected\"";
	}
	echo "<option $selected value=\"" . $genre['GenreTypeID'] . "\">" . $genre['Genre'] . "</option>";
}
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
tito85
Forum Contributor
Posts: 104
Joined: Sat Mar 13, 2010 11:26 am

Re: selected option issue

Post by tito85 »

Thanks a lot AbraCadaver.

It is now working!

Thanks again for your time!
Post Reply