user3722968
user3722968

Reputation: 43

Dynamically create variables from $_POST fields on a form

I'm having trouble creating variables from $_POST variables dynamically.

On a form, I have a table where people fill out driver information. The table has one row originally, but if more rows need to be added, the user presses a button, a new row is added, and the field names in the new row increment, i.e: driver1, driver2, driver3, driver4.

I'm trying to get this to match up with my PHP script:

$count=1; 

while($count<=100) {
  $driver . string($count) = $_POST['driver . string($count)'];
  $count++;
} 

Normally I would create a new variable for each $_POST variable, but in the case of there being up to 100 rows, I'd like to handle this with a loop.

The error I'm receiving is:

Fatal error: Can't use function return value in write context in C:\Inetpub\vhosts\host\httpdocs\process.php on line 11

Upvotes: 2

Views: 1522

Answers (3)

Andreas Storvik Strauman
Andreas Storvik Strauman

Reputation: 1655

Not reccomended to generate variables programatically. However it is possible:

${'driver'.$count}:

$count=1; 

while($count<=100) {
  ${'driver'.$count} = $_POST['driver' . $count];
  $count++;
} 

More about dynamic variables here.


I would use arrays to accomplish this though:

$driver[$count]=$_POST['driver'.$count];

Then you can do

foreach ($driver as $count => $postValue){
    // $handling here
}

// OR to access a specific driver
$driver[$count];

Upvotes: 2

martinezjc
martinezjc

Reputation: 3555

Try this

<?php

$count=1; 

while($count<=100) {
  ${'driver' . $count} = $_POST['driver' . $count];
  $count++;
}

?>

Since $count is a numeric value you don't need to do string cast.

I think this can help you to improve your code Count the number of times a specific input is present in an form

Upvotes: 1

ffflabs
ffflabs

Reputation: 17481

you can use extract to map each $_POST key to a variable of the same name.

extract($_POST,EXTR_OVERWRITE,'prefix');

This will result in variables named $prefix_driver1, $prefix_driver2... and so on.

(use of prefix is optional, but if you don't use it, a malicious user can manipulate you script variables just by changing the form's input names)

Upvotes: 0

Related Questions