Need help Populating Form with Array Values

I have a multi-dimensional array, and am having a world of trouble getting the values I need to display in my form.

In the top half of my script is PHP, and here is how I build my array…


		// ********************
		// Build Q&A Query.		*
		// ********************

		// Build query.
		$q7 = "SELECT q.id, q.question_no, q.question_text, a.answer_text
						FROM bio_question AS q
						LEFT JOIN bio_answer AS a
						ON q.id=a.question_id
						AND a.member_id =?
						ORDER BY q.question_no";

		// Prepare statement.
		$stmt7 = mysqli_prepare($dbc, $q7);

		// Bind variables to query.
		mysqli_stmt_bind_param($stmt7, 'i', $memberID);

		// Execute query.
		mysqli_stmt_execute($stmt7);

		// Store results.
		mysqli_stmt_store_result($stmt7);

		// Check # of Records Returned.
		if (mysqli_stmt_num_rows($stmt7) > 0){
			// Questions Found.

			// Bind result-set to variable.
			mysqli_stmt_bind_result($stmt7, $questionID, $questionNo, $questionText, $answerText);

			// Populate PHP array with Questions & Answers.
			$x=1;
			while (mysqli_stmt_fetch($stmt7)){
				$thoughtsArray[$x] = array('questionID' => $questionID,
												'questionText' => $questionText,
												'answerText' => $answerText);
				$x=$x+1;
			}

			echo '<pre>';
			print_r($thoughtsArray);
			echo '</pre>';

When I run that the array looks like this…


Array
(
    [1] => Array
        (
            [questionID] => 2
            [questionText] => Why did you decide to start your own business?
            [answerText] =>
        )

    [2] => Array
        (
            [questionID] => 4
            [questionText] => What advice would you share with others on what NOT to do?
            [answerText] =>
        )

    [3] => Array
        (
            [questionID] => 3
            [questionText] => What advice would you share with others on what TO do?
            [answerText] =>
        )

    [4] => Array
        (
            [questionID] => 7
            [questionText] => How do you compete against large corporations?
            [answerText] => By knowing my Customers!
        )

    [5] => Array
        (
            [questionID] => 5
            [questionText] => What Business Structure do you have?
            [answerText] =>
        )

)

You’ll notice in the Question #4, there is an Answer that I ultimately need displayed in my Form…

Down in my HTML, I am trying to loop through the array and display the Question and then the Answer in an HTML Input Field.

Here is that code…


	<form id="changeAnswers" action="" method="post">
		<fieldset>
			<legend>Change Profile Answers</legend>

			<?php
				foreach($thoughtsArray as $questionNo => $qaArray) {
					echo '<label for="question' . $questionNo . '">' . $questionNo . '.) ' . $qaArray['questionText'] . '</label>';
					echo '<textarea id="question' . $questionNo . '" name="thoughtsArray[' . $questionNo . '][\\'answerText\\']" cols="60" rows="2">' .
						(isset($questionNo]) ? "htmlentities($thoughtsArray[$questionNo]['answerText'], ENT_QUOTES" : '') .
						'</textarea>';
				}
			?>

I am able to retrieve each Question from my array, and display it.

But when I try to retrieve each Answer, I either cannot get the syntax right and I get a compile error, OR I get it to run, but no Answer will appear even though - as shown above - I do have an Answer for Question #4.

One last thing…

If I add this line of code it will display Answer #4

		echo '<p>TEST: ' . $thoughtsArray[4]['answerText'] . '</p>';

But if I add this line of code nothing appears…

		<textarea id="question4" name="thoughtsArray[4]['answerText']" cols="60" rows="2"></textarea>

So the problem clearly exists in my second echo statement in my ForEach loop…

Any ideas what I am doing wrong?! :frowning:

Thanks,

Debbie

echo ‘<textarea…>’.$qaArray[‘answerText’].‘</textarea>’;

But what about the ID? The Name?

Before I changed the name of my variables, and went to a multi-dimensional array, my hardcoded Inputs looked like this…


	<!-- Question 3 -->
	<label for="question3">3.) What advice would you share with others on what NOT to do?</label>
	<textarea id="question3" name="answerArray[3]" cols="60" rows="2"><?php if (isset($answerArray[3])){echo htmlentities($answerArray[3], ENT_QUOTES);} ?></textarea>
	<?php
		if (!empty($errors[3])){
			echo '<br /><span class="error">' . $errors[3] . '</span>';
		}
	?>
<br />

This is what I now have for my Label, but I need the Inputs to match up…


	echo '<label for="question' . $questionNo . '">' . $questionNo . '.) ' . $qaArray['questionText'] . '</label>';

Hope you follow what I’m saying?!

Debbie

The … indicates where you fill in the relevant attributes yourself.

Right, but I have isn’t working yet… :wink:

I tried using what you posted, and it works for populating the field, but to get things where they need to be, my code still isn’t working.

Here is what I have so far with the offending code commented out…


	<?php

		foreach($thoughtsArray as $questionNo => $qaArray) {
			echo '<label for="question' . $questionNo . '">' . $questionNo . '.) ' . $qaArray['questionText'] . '</label>';


			echo "<textarea id=\\"question" . $questionNo . " name=\\"thoughtsArray[$questionNo][\\"answerText\\"]\\" cols=\\"60\\" rows=\\"2\\">" .
//				(isset($questionNo) ? "htmlentities($qaArray['answerText'], ENT_QUOTES" : '') .
				$qaArray['answerText'] . 
				"</textarea>";

It seems like it is the single quotes around answerText that keep causing most of the issues?!

What am I doing wrong?

Also, what should I have in the isset()?

I am a little unclear as to what I am checking for…

Thanks,

Debbie

Hi Debbie,

I did your thing like this:

 
<?php
if($_POST['submit']){
  var_dump($_POST);
}
$outer = array();
$outer[] = Array
        (
            'questionID' => 2
            ,'questionText' => 'Why did you decide to start your own business?'
            ,'answerText' => 'I disliked my boss and I learned how to do it myself.'
        );
$outer[] = Array
        (
            'questionID' => 7
            ,'questionText' => 'How do you compete against large corporations?'
            ,'answerText' => 'By knowing my Customers!'
        );
$html ="<form action=" . $_SERVER['PHP_SELF'] . " method='post'>";
$q_num = 0;
foreach ($outer as $key => $array){
  foreach($array as $key => $value){
    if($key == 'questionID'){
      $q_num = $value;
    }
    switch($key){
      case 'questionText':
        $html .= "<label for='question$q_num'/>$value</label><br />";
        break;
      case 'answerText':
        $html .=<<<CODE
        <textarea name='thoughtsArray[$q_num]'>
         $value
        </textarea><br />
CODE;
        break; 
    }
    
  }
}
$html .=     '<input type="submit" name="submit" value="submit">'; 
$html .= '</form>';
echo $html;
?>

Before submitting this form, the html that is render - echo $html - looks like:

 
<form action=/test.php method='post'>
  <label for='question2'/>Why did you decide to start your own business?</label>
  <br /> 
  <textarea name='thoughtsArray[2]'>
    I disliked my boss and I learned how to do it myself.
  </textarea>
  <br />
  <label for='question7'/>How do you compete against large corporations?</label>
  <br /> 
  <textarea name='thoughtsArray[7]'>
   By knowing my Customers!
  </textarea><br />
  <input type="submit" name="submit" value="submit">
</form>

And the output is:

array(2) { [“thoughtsArray”]=> array(2) { [2]=> string(72) " I disliked my boss and I learned how to do it myself. " [7]=> string(43) " By knowing my Customers! " } [“submit”]=> string(6) “submit” }
The keys of the ‘thoughtsArray’ are equal to the questionIDs with their corresponding answer.

The <br /> is a bad way to get the form laid out properly. CSS should be used to do this however for this example it was just quick to do this.

You could also ensure in the foreach loops that you don’t include any questions or answers that do not have an answer by checking if the answer value is empty and then not adding it to the $html.

The <<<CODE and CODE; is using heredoc syntax so I could make the quotes cleaner without having to tie everything together with periods and single quotes inside double quotes.

I hope this helps.
Steve

For the purposes of displaying things, this code seems to be working…


	<?php
		foreach($thoughtsArray as $questionNo => $qaArray){
			echo '<label for="question' . $questionNo . '">' . $questionNo . '.) ' . $qaArray['questionText'] . "\
";

			echo '<textarea id="question' . $questionNo . '" name="' . $qaArray["questionID"] . '" cols="60" rows="2">';
			echo (isset($questionNo) ? htmlentities($qaArray['answerText'], ENT_QUOTES) : '');
			echo "</textarea>\
\
";
		}
	?>

Debbie