Page 1 of 1

This small foreach loop is giving me trouble, see a problem?

Posted: Sat May 29, 2004 5:39 pm
by idotcom
Hi all..

After finally resolving one problem, I ran into another that is so bugging me. This loop will not run the update query everytime through it, only at the end of the loop. Can anyone please tell me why?

Code: Select all

<? 

if($_POST) 

{ 

   mysql_connect("$db_host", "$db_user", "$db_pass") or die ("DataBase connection error! Please try again later"); 

   foreach (array_keys($_POST) as $key) 

{ 

   $$key = $_POST[$key]; 

   $link_id = $key;            ///<- printing this
   $link_order = ${$key}; ///<- and this both work in every iteration

   // This query won't update on every loop, just last iteration

   $query="UPDATE menu SET link_order='$link_order' WHERE link_id='$link_id'"; 

} 

   mysql_db_query($db_db,$query); 

} 

?>
So the foreach loop above takes all the "variable variables" form inputs and processes them. This is what the input looks like.. populated in a while loop.

Code: Select all

&lt;input type="text" name="&lt;?=$link_id?&gt;" value="&lt;?=$link_order?&gt;" maxlength="3" size="3"&gt;
Now if I put a ( print "$link_id has the value $link_order"; ) above or below the UPDATE query, it prints just fine. But in the UPDATE query, using the same variables, it only updates the last one in the loop.

If anyone can help with this I would greatly appreciate it!

Thank you

Posted: Sat May 29, 2004 6:23 pm
by scorphus
On this line:

Code: Select all

$query="UPDATE menu SET link_order='$link_order' WHERE link_id='$link_id'";
you are just setting your query string, mysql_db_query($db_db,$query); is who does the job and send the query to the MysQL DB Server. So place it inside the foreach loop just after setting the query string.

Just a note:
mysql_db_query() reference wrote:Note: This function has been deprecated since PHP 4.0.6. Do not use this function. Use mysql_select_db() and mysql_query() instead.
Scorphus.

Posted: Sat May 29, 2004 6:52 pm
by idotcom
Sweet!

right on Scorphus thank you.

Re: This small foreach loop is giving me trouble, see a prob

Posted: Mon May 31, 2004 10:09 am
by pickle
An easier way to do this:
idotcom wrote: foreach (array_keys($_POST) as $key)
is:

Code: Select all

foreach($_POST as $key=>$value)
So, if you had $_POST['submit'] = "Submit Button", then $key would get 'submit' and $value would get "Submit Button".