2

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
3
  • What's your goal here: $driver . string($count) = $_POST['driver . string($count)'];? You have an assignment = $_POST... in the middle of a concatenation. Commented Jun 9, 2014 at 16:01
  • 1
    Ohhh I get it. You're trying to build variable variables. Why not just keep them in an array? They are, after all, related. They are better organized inside a data structure. Commented Jun 9, 2014 at 16:04
  • @MichaelBerkowski - I foresee a large number of isset calls... Commented Jun 9, 2014 at 16:09

3 Answers 3

2

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];
Sign up to request clarification or add additional context in comments.

1 Comment

I'm pretty sure OP meant $_POST['driver' . string($count)] unless they actually have post fields called driver . string(42).
1

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.