Jump to content


Photo

Getting form input without creating variables


  • Please log in to reply
13 replies to this topic

#1 Colin-uk

Colin-uk
  • Members
  • Pip
  • Newbie
  • 4 posts

Posted 23 October 2006 - 03:26 PM

Ok so normally when coding something to get values from a form i usually use this code:

$varname = $_POST['name'];

so then i can do what i want with $varname

but say for example I had 200+ form fields to get input from, would there be anyway of getting the form input without having to type a $varname out for each of them?

Im not sure how i could do this so any help would be appreciated :)

Thanks,
Colin



#2 trq

trq
  • Staff Alumni
  • Advanced Member
  • 31,041 posts

Posted 23 October 2006 - 03:30 PM

Not sure what context your working in but you can easily loop through the post array.

foreach($_POST as $key => $val) {
  echo "key ($key) = val ($val)";
}


#3 underparnv

underparnv
  • Members
  • PipPipPip
  • Advanced Member
  • 30 posts
  • LocationReno, Nevada

Posted 23 October 2006 - 03:35 PM

You could always use the extract function as well...though it isn't the most secure method...

<?php
extract($_POST);
?>

Now for every posted value, the name becomes your variable name.  For example, say you posted the following:

<input type="text" name="test" value="" />

You would then get a variable $test.
"Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning."

The Sporting Edge - Free NFL Football Pool


#4 .josh

.josh
  • Staff Alumni
  • .josh
  • 14,871 posts

Posted 23 October 2006 - 03:41 PM

foreach($_POST as $key => $val) {
  echo $$key = $val;
} 

though extract does pretty much the same thing.  here is what i usually do, more or less:

<?php
// prevent sql injection
function clean_var($value){
   if (get_magic_quotes_gpc()) { stripslashes($value); }
   if (!is_numeric($value)) { mysql_real_escape_string($value); }    
   return $value;
} // end clean_var

// clean the variables of potential malicious code 
// and create variables named by their key names 
foreach($_POST as $key => $val) {
   $val = clean_var($val);         
   $$key = $val;
} // end foreach $_POST
?>

Did I help you? Feeling generous? Buy me lunch! 
Please, take the time and do some research and find out how much it would have cost you to get your help from a decent paid-for source. A "roll-of-the-dice" freelancer will charge you $5-$15/hr. A decent entry level freelancer will charge you around $15-30/hr. A professional will charge you anywhere from $50-$100/hr. An agency will charge anywhere from $100-$250/hr. Think about all this when soliciting for help here. Think about how much money you are making from the work you are asking for help on. No, we do not expect you to pay for the help given here, but donating a few bucks is a fraction of the cost of what you would have paid, shows your appreciation, helps motivate people to keep offering help without the pricetag, and helps make this a higher quality free-help community :)

#5 Colin-uk

Colin-uk
  • Members
  • Pip
  • Newbie
  • 4 posts

Posted 23 October 2006 - 04:17 PM

hmm that extract function looks pretty handy :)

if I use the foreach method do i get pretty much the same results? (the name becomes the variable)

Thanks,
Colin


#6 roopurt18

roopurt18
  • Staff Alumni
  • Advanced Member
  • 3,749 posts
  • LocationCalifornia, southern

Posted 23 October 2006 - 05:09 PM

Just out of curiosity, what kind of form is this?  Are you sure it needs 200+ fields?
PHP Forms : Part I | Part II

JavaScript: Singleton

http://www.rbredlau.com

#7 Colin-uk

Colin-uk
  • Members
  • Pip
  • Newbie
  • 4 posts

Posted 23 October 2006 - 05:17 PM

its actually 232 Fields (just counted them :P) Im creating a sortof online profession portfolio builder..

I think I have it figured out now though (ive never fully got my head around arrays and functions like foreach(); and while(); )

does this code look valid? :P

<?php

include("dbconnect.php"); //db connection

foreach($_POST as $key => $val) {

mysql_query("INSERT INTO dbname (ID, LinkID, $key) VALUES ('','','$val')") or die(mysql_error());

}

?>

-Colin


#8 HuggieBear

HuggieBear
  • Members
  • PipPipPip
  • Advanced Member
  • 1,899 posts
  • LocationEngland, UK

Posted 23 October 2006 - 05:26 PM

That syntax looks fine.

You might want to sanitise the input first of all, search here for terms such as "SQL injection" and "Sanitise" or "Sanitize".

Regards
Huggie
Advice to MySQL users: Get phpMyAdmin and test your queries work there first, take half the hassle out of diagnosis, also check the reserved words list.

Links: PHP Docs :: RegEx's :: MySQL :: DevGuru :: w3schools

#9 Colin-uk

Colin-uk
  • Members
  • Pip
  • Newbie
  • 4 posts

Posted 23 October 2006 - 05:42 PM

Thanks HuggieBear :)


But I just realised I posted the wrong code  :-[  Sorry.
This is the code i'll be attempting to use:

<?php

include("dbconnect.php");

$id = $_POST['id'];

foreach($_POST as $key => $val) {

mysql_query("UPDATE dbname SET $key = '$val' WHERE id = '$id'") or die(mysql_error());

}

?>

Although, im not sure how im going to pass the $id to the script, securely..  :-\



#10 .josh

.josh
  • Staff Alumni
  • .josh
  • 14,871 posts

Posted 23 October 2006 - 07:25 PM

sanitizing variables means you check them for potentially malicious code. see my previous post where i have the clean_var function for an example
Did I help you? Feeling generous? Buy me lunch! 
Please, take the time and do some research and find out how much it would have cost you to get your help from a decent paid-for source. A "roll-of-the-dice" freelancer will charge you $5-$15/hr. A decent entry level freelancer will charge you around $15-30/hr. A professional will charge you anywhere from $50-$100/hr. An agency will charge anywhere from $100-$250/hr. Think about all this when soliciting for help here. Think about how much money you are making from the work you are asking for help on. No, we do not expect you to pay for the help given here, but donating a few bucks is a fraction of the cost of what you would have paid, shows your appreciation, helps motivate people to keep offering help without the pricetag, and helps make this a higher quality free-help community :)

#11 HuggieBear

HuggieBear
  • Members
  • PipPipPip
  • Advanced Member
  • 1,899 posts
  • LocationEngland, UK

Posted 23 October 2006 - 08:54 PM

Thanks HuggieBear :)

But I just realised I posted the wrong code  :-[  Sorry.
This is the code i'll be attempting to use:

<?php
include("dbconnect.php");
$id = $_POST['id'];

foreach($_POST as $key => $val) {
   mysql_query("UPDATE dbname SET $key = '$val' WHERE id = '$id'") or die(mysql_error());
}
?>


OK, if you're taking the 'id' seperately then you'll not want it in the foreach, you'll want a condition to exclude it, so try this...

<?php
include("dbconnect.php");
$id = $_POST['id'];

foreach($_POST as $key => $val) {
   if ($key != "id"){
      mysql_query("UPDATE dbname SET $key = '$val' WHERE id = '$id'") or die(mysql_error());
   }
}
?>

Advice to MySQL users: Get phpMyAdmin and test your queries work there first, take half the hassle out of diagnosis, also check the reserved words list.

Links: PHP Docs :: RegEx's :: MySQL :: DevGuru :: w3schools

#12 Jenk

Jenk
  • Members
  • PipPipPip
  • Advanced Member
  • 778 posts

Posted 23 October 2006 - 09:02 PM

232 queries in one page request.. I'd hate to be your host, and one of your users..

and for the record, you do not need to reassign a POST var before using it, you can use $_POST['var'] just like any other variable..

#13 .josh

.josh
  • Staff Alumni
  • .josh
  • 14,871 posts

Posted 23 October 2006 - 09:03 PM

^ no doubt, lol..
Did I help you? Feeling generous? Buy me lunch! 
Please, take the time and do some research and find out how much it would have cost you to get your help from a decent paid-for source. A "roll-of-the-dice" freelancer will charge you $5-$15/hr. A decent entry level freelancer will charge you around $15-30/hr. A professional will charge you anywhere from $50-$100/hr. An agency will charge anywhere from $100-$250/hr. Think about all this when soliciting for help here. Think about how much money you are making from the work you are asking for help on. No, we do not expect you to pay for the help given here, but donating a few bucks is a fraction of the cost of what you would have paid, shows your appreciation, helps motivate people to keep offering help without the pricetag, and helps make this a higher quality free-help community :)

#14 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 23 October 2006 - 09:21 PM

If you're going to do one mysql_query call for each field, the processing script is going to take forever. My advice is to create one large query to execute.

If all of the fields are of the same type and are validated in the same manor, you can just use the foreach loop, but if there are a variety of different fields with different validation criteria, add a switch statement to the foreach and group each field type.

Both of these techniques assume that the field names in your form match those in the database.

Here's a short example using the switch method:
<?php
$tmpq = array();
$whr = '';
foreach($_POST as $key => $val) {
    switch($key) {
        case 'id':
             $whr = "where id='" . mysql_real_escape_string($val) . "'";
             break;
        case 'submit': // ignore the submit button
             break;
        case 'textfld1':
        case 'textfld2':
             if (strlen(trim(stripslashes($val))) > 0)
                  $tmpq[] = $key . " = '" . mysql_real_escape_string(trim(stripslashes($val))) . "'"
             break;
        case 'date1':
        case 'date2':
             $tmpq[] = $key . " = '" . date('Y-m-d',strtotime($val)) . "'"; // you probably want to validated this field first
             break;
    }
}
if (!empty($tmpq)) {
   $q = "update tablename set " . implode(', ',$tmpq) . $whr;
   $rs = mysql_query($q) or die("Problem with query: $q<br>" . mysql_error());
}
?>

Note:  I just typed this in, so there are probably errors

Ken




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users