0

I have a save.php page that is being called using Ajax, it contains the following elements:

$q1 = $_POST["q1"];
$q2 = $_POST["q2"];
$q3 = $_POST["q3"];
$q4 = $_POST["q4"];
$q5 = $_POST["q5"];

$proc = mysqli_prepare($link, "INSERT INTO tresults 
(respondent_id, ip, browser, company, q1, q2, q3, q4, q5) 
VALUES (?, ?, ?, ?, ?, ?, ?, ?);");

mysqli_stmt_bind_param($proc, "issiiiii", 
$respondent_id, $ip, $browser, $company, 
$q1, $q2, $q3, $q4, $q5);

At the moment, the save.php page is manually coded but I am sure there must be a way of using variable variables to automate this page to a degree, especially when the number of fields exceeds 100 that I am saving to the database.

I am, however, having trouble getting my head around using variable variables and could use some guidance.

I am have, to no avail, tried the following:

for ($i = 1; $i <= 5; $i++) {
    echo '$q.$i = $_POST["q".$i];';
}

and also

for ($i = 1; $i <= 5; $i++) {
   $q.$i = $_POST["q".$i];
}

Any and all advice welcomed.

Thanks.

Homer_J
  • 3,277
  • 12
  • 45
  • 65
  • 1
    `${'q'.$i} = $_POST['q'.$i];` – Deadooshka May 15 '14 at 04:54
  • `$var = "q$i"; $$var = $_POST[$var];`. But seriously, look into naming your form fields better. – cHao May 15 '14 at 04:55
  • 1
    Even if you do this, I guess there will be a scope issue since they are being declared inside the loop, I suggest you name your fields as `q[]` that way the system auto-indexes your fields and you can loop through them easy. – AyB May 15 '14 at 04:56
  • Yeah, what he said. :) – cHao May 15 '14 at 04:57
  • @ICanHasKittenz - thanks for the feedback - do you have any further information you can point me too? – Homer_J May 15 '14 at 05:16
  • 1
    @Homer_J Have a look at [this answer](http://stackoverflow.com/a/1010970/2513523). It's using a checkbox but the same can be implemented for any other input/select. – AyB May 15 '14 at 05:29

2 Answers2

2

You can use:

${'q'.$i} = $_POST['q'.$i];

Also:

for ($i = 1; $i <= 5; $i++) {
    echo '$q.$i = $_POST["q".$i];';
}

should be:

for ($i = 1; $i <= 5; $i++) {
    echo "$q.$i = $_POST['q'.$i];";
    //   ^                       ^
}

otherwise variables won't be interpolated within the string.

Shoe
  • 74,840
  • 36
  • 166
  • 272
0

Wrap them in {} like

for ($i = 1; $i <= 5; $i++) {
${'q'.$i}=$_POST['q'.$i];
}

Please got through this once for reference http://www.php.net/manual/en/language.variables.variable.php

Jenz
  • 8,280
  • 7
  • 44
  • 77