Page 1 of 1

How to pass more than one row to another page

Posted: Wed Dec 29, 2010 10:49 am
by rubendoliveira
Hi,

I have a select box where I show the names of each category and I want to pass the id of the selected category to my script.php page. The problem is that $id_category gets only the id of the last category on my database. I know that this happens due to the while loop. I just don't know how to fix the situation.

Any ideas?

Code: Select all

<form method="POST" action="script.php">
	<?php 
	echo "<select>";
	while ($row = mysql_fetch_assoc($result)) {
		echo "<option>" . $row['name'] ."</option>";
		$id_category= $row["id_category"];
	}
	echo "</select>";
	echo "<input type=\"hidden\" name=\"id_category\" value=\"$id_category\" />";
	echo "<input type=\"submit\" value=\"Submit\">";
	?>

Thanks in advance.

Re: How to pass more than one row to another page

Posted: Wed Dec 29, 2010 11:06 am
by josh
One way to do this is append "[]" to the name of the form element, and move it inside the loop (so it will output multiple times). All the values will be sent as an array.

The other way is to build up your own array and serialize it (or build up a comma delimited string, and output that as the value).

Look into explode() and implode() for example.

Re: How to pass more than one row to another page

Posted: Wed Dec 29, 2010 12:40 pm
by rubendoliveira
I am sorry, can you give me an example? I tried to work with arrays but I was doing it wrong.

Re: How to pass more than one row to another page

Posted: Wed Dec 29, 2010 12:47 pm
by josh

Code: Select all

$array = array();
while ($row = mysql_fetch_assoc($result)) {
  $array[] = $row;
  
  # this part passes an array over GET/POST parameters. On the next page $_GET['array'] will be the same as $array
  $id = 'whatever';
  echo '<input type="hidden" name="array[]" value="' . $id . '" />';
}
print_r($array);
Another way

Code: Select all

$array = array();
while ($row = mysql_fetch_assoc($result)) {
  $array[] = $row;
}

#use unserialize() on next page
echo '<input type="hidden" name="array" value="' . serialize($array) . '" />';
print_r($array);