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.

6
  • 1
    ${'q'.$i} = $_POST['q'.$i]; Commented May 15, 2014 at 4:54
  • $var = "q$i"; $$var = $_POST[$var];. But seriously, look into naming your form fields better. Commented May 15, 2014 at 4: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. Commented May 15, 2014 at 4:56
  • Yeah, what he said. :) Commented May 15, 2014 at 4:57
  • 1
    @Homer_J Have a look at this answer. It's using a checkbox but the same can be implemented for any other input/select. Commented May 15, 2014 at 5:29

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

@Jefffrey..sorry I didn't see your answer while I was posting this.

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.