Search code examples
phporacleoci8

How can I iterate through unique variable names when inserting values into Oracle?


In my PHP code, I have variables named/defined like this:

$comment_1 = $_POST["A_comment"];
$comment_2 = $_POST["B_comment"];
$comment_3 = $_POST["C_comment"];

I'm attempting to insert the values from these variables into Oracle using an iterative approach to provide the number being used at the end of each variable name, as shown here:

for($i=1;$i<4;$i++) {
    $sql2 = "INSERT INTO i_avail(IA_COMMENTS) VALUES('$comment_$i')";
    $stid2 = oci_parse($connect, $sql2);
    $r = oci_execute($stid2);
}

Instead of inserting the expected value from the three $POST references (text only), three numbers are inserted into the table (numbers 1,2 and 3). I'm guessing that this is occurring because $comment can't be found, and uses $i instead for the value. In other words, it's not processing the variable name as I had hoped.

How can I configure the variable name in my INSERT statement so that it recognizes my variable names as "$comment_1", "$comment_2" and "$comment_3"? Do I need to use different quotes, or escape something?


Solution

  • $comment_$i in your code is not the correct way of initializing a variable that's why it shows wrong value. This should do the trick. Dynamic variable generation is the term used for this.

    for($i=1;$i<=4;$i++) {
        $variable = ${"comment_" . $i};
        $sql2 = "INSERT INTO i_avail(IA_COMMENTS) VALUES('$variable')";
    }