Jump to content

Archived

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

Colin-uk

Getting form input without creating variables

Recommended Posts

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

[code]$varname = $_POST['name']; [/code]

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

Share this post


Link to post
Share on other sites
Not sure what context your working in but you can easily loop through the post array.

[code=php:0]
foreach($_POST as $key => $val) {
  echo "key ($key) = val ($val)";
}
[/code]

Share this post


Link to post
Share on other sites
You could always use the [url=http://us2.php.net/manual/en/function.extract.php]extract function[/url] as well...though it isn't the most secure method...

[code]
<?php
extract($_POST);
?>
[/code]

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

[code]
<input type="text" name="test" value="" />
[/code]

You would then get a variable $test.

Share this post


Link to post
Share on other sites
[code]
foreach($_POST as $key => $val) {
  echo $$key = $val;
}
[/code]

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

[code]
<?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
?>
[/code]

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
Just out of curiosity, what kind of form is this?  Are you sure it needs 200+ fields?

Share this post


Link to post
Share on other sites
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

[code]
<?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());

}

?>
[/code]

-Colin

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
Thanks HuggieBear :)


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

[code]
<?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());

}

?>
[/code]

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

Share this post


Link to post
Share on other sites
sanitizing variables means you check them for potentially malicious code. see my previous post where i have the clean_var function for an example

Share this post


Link to post
Share on other sites
[quote author=Colin-uk link=topic=112440.msg456435#msg456435 date=1161625366]
Thanks HuggieBear :)

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

[code]
<?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());
}
?>
[/code][/quote]

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...

[code]
<?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());
  }
}
?>
[/code]

Share this post


Link to post
Share on other sites
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..

Share this post


Link to post
Share on other sites
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:
[code]<?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());
}
?>[/code]

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

Ken

Share this post


Link to post
Share on other sites

×

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.