Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top