How to pass more than one row to another page

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
rubendoliveira
Forum Newbie
Posts: 4
Joined: Tue Dec 28, 2010 8:04 am

How to pass more than one row to another page

Post 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.
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

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

Post 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.
rubendoliveira
Forum Newbie
Posts: 4
Joined: Tue Dec 28, 2010 8:04 am

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

Post by rubendoliveira »

I am sorry, can you give me an example? I tried to work with arrays but I was doing it wrong.
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

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

Post 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);
Post Reply