Jump to content

simplifying code ... foreach??


severndigital

Recommended Posts

I am going through my exisiting code for a new version of my application.

 

I need to process the results of form fields currently I do it like this.

 


$var1 = $_POST['field1'];
$var2 = $_POST['field2'];

 

I don't mind this method except that I have to process 15 - 20 fields on each submit. So, I have to cut and paste this code over and over again and modify the vars and field names for each submit.

 

is there an easy way to process the fields and assign variables  to them, based on the name of the field processed?

 

I am thinking I should use a foreach statement, but I am not sure exactly how to use it properly or if it can automatically assign field names and values.

 

I supposed I could run an sql query to get the proper field names and then build the post statements dynamically based off of that information.

 

Anyway .. any thoughts or suggestions on this one, would be much appreciated.

 

Thanks,

Chris

 

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/41705-simplifying-code-foreach/
Share on other sites

Look below.

 

Your HTML form would look something like this:

<form action="mypage.php" method="post">
    <input type="text" name="field[]" />
    <input type="text" name="field[]" />
    <input type="text" name="field[]" />
    <input type="submit" name="submit" value="Submit" />
</form>

 

Your PHP page would look something like this:

<?php
if ( isset( $_POST['submit'] ) ) {
    foreach ( $_POST['field'] as $key=>$val ) {
        "Field: $key has a value of '$val'";
    }
}
?>

Ok, i've grasped the idea of using for each to get the variables from the $_POST command. But how do I incorperate them into a DB Query?

 

 

assume for this that I am auto collecting username and password, then I would like to use them in a mysql query

here's what i have so far:

 

<?
//grab all fields from the form
foreach($_POST['field'] as $key => $val){

}

//I know the mysql query would like this.

$user_check = mysql_query("SELECT * FROM users WHERE username='$whatgoeshere' AND password='$whatgoeshere'");
?>

I just don't know how to get the form fields to interact with other code together.

 

the foreach loop seems to want to make them work independently of each other.

 

Is what I want to do here possible? or should I just be hard coding this. The above is one example. I would also like to put this in place for updating information in the db and also passing the information through multiple forms.

 

any help would be great.

 

thanks,

chris

 

 

 

 

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.