user3506743
user3506743

Reputation: 45

Three page sequence of forms (checkboxes and text/number boxes) with foreach in php

I would like to pass variables through 3 pages. The 1st page asks the user which music genres they like (there will eventually be 20+ genres). The 2nd page asks the user to rank the genres they have selected and the 3rd page sorts and displays their ranking.

This first page asked the user to pick which genres they like:

 <form id="genre" name="genre" method="post" action="musicsell.php">
  <input type="checkbox" name="genre[]" value="Rap"/>Rap<br />
  <input type="checkbox" name="genre[]" value="HipHop"/>HipHop<br />
  <input type="checkbox" name="genre[]" value="RnB"/>RnB<br />
  <input type="checkbox" name="genre[]" value="Rock"/>Rock<br />
  <input type="checkbox" name="genre[]" value="Jazz"/>Jazz<br />

  <p>
    <input type="submit" value="Next">
    <br />
  </p>
</form>

This second asks them to rank (prioritize) the genres they have selected with 1 being the best:

<body>
The genre(s) you selected are: <br>
<form id="form1" name="form1" method="post" action="musicresults.php">
<?php
$name = $_POST['genre'];

if(isset($_POST['genre'])) {
foreach ($name as $genre){

?>

<input 
type="number" required="required" id="<?php echo $genre ?>" name="music[<?php echo $genre ?>]" />
<?php echo $genre ?><br /> 

<?php
    }
} 
?>

<input type="submit" name="button" id="button" value="Submit" /></form>
</body>

The third and last page sorts and echos the results:

<?php
//Get the form results (which has been converted to an associative array)     from the $_POST super global
$musicgenres = $_POST['music'];

//Sort the values by rank and keep the key associations.
asort($musicgenres, SORT_NUMERIC );

//Loop over the array in rank order to print out the values.
foreach($musicgenres as $music => $rank)
{
   echo "$musicgenres is your $rank choice";
   echo "<br>";
}
?>

It all works fine until the last page where I'm getting an "array to string conversion" error. Maybe I need to put in session variables but I'm not sure.

Any help would be appreciated.

Upvotes: 1

Views: 65

Answers (1)

Jo Smo
Jo Smo

Reputation: 7169

It's exactly what the error says. It can't convert and array to a string.

Replace

echo "$musicgenres is your $rank choice"; 

with

echo "$music is your $rank choice";

Upvotes: 2

Related Questions