Ahmed Ebaid
Ahmed Ebaid

Reputation: 417

Passing an array in PHP to another PHP script through html hidden form element

My question is that when I copy my array elements between different php scripts using session variables, nothing gets printed out. The following are my two php files.

file1.php

   $SQL = "SELECT * FROM tblquestions";
if ($db_found) {
        $result = mysql_query($SQL);
        $numRows = mysql_num_rows($result); //return number of rows in the table
        echo '<FORM NAME ="form1" METHOD ="POST" ACTION ="file2.php">';
        for ($i = 1; $i <= 2; $i++)
        {
            $db_field = mysql_fetch_assoc($result);
            $qID[$i] = $db_field['QID'];
            $question[$i] = $db_field['Question'];
            $A[$i] = $db_field['qA'];
            $B[$i] = $db_field['qB'];
            $C[$i] = $db_field['qC'];
            echo '<P>';
            print $question[$i];
            echo '<P>';
            echo "<INPUT TYPE = 'Radio' Name = '".$qNum."'  value= 'A'>"; 
            print $A[$i];
            echo '<P>';
            echo  "<INPUT TYPE = 'Radio' Name = '".$qNum."'   value= 'B'>"; 
            print $B[$i];
            echo '<P>';
            echo  "<INPUT TYPE = 'Radio' Name = '".$qNum."'   value= 'C'>"; 
            print $C[$i];
            //if (isset($_POST[$name_Value]))
            $survey_Answers[$i-1] = $_POST[$qNum];
            print '</BR>'.$survey_Answers[$i-1]."</BR>";
            $question_Number = ltrim($qNum,'q');
            $question_Number++;
            $qNum ='q'.$question_Number;
        }

        echo '<p>';
    session_start();
    $_SESSION['answers'] = $survey_Answers;
        echo '<INPUT TYPE = "Submit" Name = "Submit1"  VALUE = "Click here to vote">';

        echo '</form>';

On my Second file (file2.php), I have the following:

<?PHP
session_start();
if (isset($_POST['Submit1'])) {
        $results = $_SESSION['answers'];
        print $results[0];
?>

Nothing gets printed out when executing the above code.

Thanks in advance

Upvotes: 0

Views: 467

Answers (1)

Drew
Drew

Reputation: 4373

I am pretty sure that the session values stored need to be strings.

In file1.php change:

$_SESSION['answers'] = $survey_Answers;

to this:

$_SESSION['answers'] = json_encode($survey_Answers);

Then in file2.php change:

$results = $_SESSION['answers'];

to this:

$results = json_decode($_SESSION['answers']);

Upvotes: 1

Related Questions