Jump to content

Problem with Array in Form and Trim


doubledee

Recommended Posts

I have a Form with 10 Questions that a User can choose to answer.

 

I am trying to store the "Answers" into an array like this...

<!-- Question 1 -->
<label for="question1">1.) Why did you decide to start your own business?</label>
<textarea id="question1" name="answerArray[0]" cols="60" rows="8"><?php if (isset($answerArray[0])){echo htmlentities($answerArray[0], ENT_QUOTES);} ?></textarea>
<?php
	if (!empty($errors['question1'])){
		echo '<br /><span class="error">' . $errors['question1'] . '</span>';
	}
?>
<br />

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

 

 

The problem is that when I process the Form, this code is causing issues...

if ($_SERVER['REQUEST_METHOD']=='POST'){
	// Form was Submitted (Post).

	// Initialize Errors Array.
	$errors = array();

	// Trim all form data.
	$trimmed = array_map('trim', $_POST);

 

I get this error...

Notice: Array to string conversion in /Users/user1/Documents/DEV/++htdocs/05_Debbie/members/create_thoughts.php on line 58
Call Stack
#	Time	Memory	Function	Location
1	0.0014	93944	{main}( )	../create_thoughts.php:0
2	0.0716	102640	array_map ( )	../create_thoughts.php:58

 

 

How can I either fix my code or change things to do what I need?

 

Thanks,

 

 

Debbie

 

Link to comment
Share on other sites

if (isset($_POST)){
$answerArray=array();
foreach($_POST['answerArray'] as $k =>$v){
$answerArray[$k]=trim($v);
}
}

 

Thanks for the response, Drummin, but I am still really confused here...  :-[

 

Some questions...

 

1.) How should the fields in my form look?

 

Is this code okay...

<!-- Question 1 -->
<label for="question1">1.) Why did you decide to start your own business?</label>
<textarea id="question1" name="answerArray[0]" cols="60" rows="8"><?php if (isset($answerArray[0])){echo htmlentities($answerArray[0], ENT_QUOTES);} ?></textarea>
<?php
	if (!empty($errors['question1'])){
		echo '<br /><span class="error">' . $errors['question1'] . '</span>';
	}
?>
<br />

 

 

2.) This syntax doesn't look right to me.

 

Why isn't there an index on this code...

foreach($_POST['answerArray'] as $k =>$v){

 

Shouldn't it be...

foreach($_POST['answerArray[somethingHere]'] as $k =>$v){

 

(I'm not very strong with Arrays...)

 

 

Debbie

 

Link to comment
Share on other sites

As far as your textarea names,  name="answerArray[0]" etc. these look right.

 

The "foreach" is going to grab that zero that's within the brackets or 0 from example above, and define it AS $k.

 

if you add this to the top of your page is will make things more clear.

echo "<pre>";
print_r($_POST);
echo "</pre>";

You'll see the post is an array but also the name "answerArray" is an array with Keys and Values.

What the foreach does, is assign these keys and values to variables that you can use.

 

So if for example your form has  name="answerArray[22]",  the foreach will say the Key($k) is 22 and the Value($v) is the content for this key.

foreach($_POST['answerArray'] as $k =>$v){

 

You then do what you want with these variables, in this case you want an array named $answerArray.

You assign the Key,

$answerArray[$k]

then say the value for this Key

$answerArray[$k]=$v;

 

But you also want to trim this value so you add trim()

$answerArray[$k]=trim($v);

 

Hope that helps

 

Link to comment
Share on other sites

Drummin,

 

Sorry I'm having such a hard time with this...

 

Let me try again...

 

My php script is set up with the php at the top of the file and HTML at the bottom.

 

When the script is loaded, the first time things drop straight down to the HTML Form where I have...

<!-- Question 1 -->
<label for="question1">1.) Why did you decide to start your own business?</label>
<textarea id="question1" name="answerArray[0]" cols="60" rows="8"><?php if (isset($answerArray[0])){echo htmlentities($answerArray[0], ENT_QUOTES);} ?></textarea>
<?php
	if (!empty($errors['question1'])){
		echo '<br /><span class="error">' . $errors['question1'] . '</span>';
	}
?>
<br />

 

Now, do I have an Array at this point?

 

What does this do when the Form is loaded...

<textarea id="question1" name="answerArray[0]" 

 

 

To me, it looks sorta like I am creating an Array here?!  :confused:

 

And what happens when the User types "I want to run my own business because..." in the first Form Field?

 

 

Now let's say the User clicks "Submit" and so my script is loaded onto itself, and now the PHP at the top of my script kicks in here...

// *************************************************************
// HANDLE FORM.								*
// *************************************************************
if ($_SERVER['REQUEST_METHOD']=='POST'){
	// Form was Submitted (Post).

 

 

So this is where your original code began.  And looking at your code again...

if (isset($_POST)){
$answerArray=array();
foreach($_POST['answerArray'] as $k =>$v){
$answerArray[$k]=trim($v);
}
}

 

 

If the Form is submitted, we initialize an array called $answerArray(), right?

 

Doesn't that erase what we did in the Form above?

 

 

In this code...

foreach($_POST['answerArray'] as $k =>$v){

 

What is happening here?

 

Is 'answerArray' the array I thought I was creating in the Form code here...

<!-- Question 1 -->
<label for="question1">1.) Why did you decide to start your own business?</label>
<textarea id="question1" name="answerArray[0]" cols="60" rows="8"><?php if (isset($answerArray[0])){echo htmlentities($answerArray[0], ENT_QUOTES);} ?></textarea>
<?php
	if (!empty($errors['question1'])){
		echo '<br /><span class="error">' . $errors['question1'] . '</span>';
	}
?>
<br />

 

 

What is in $_POST at this point?

 

Based on my Form, I am thinking there is...

 

$_POST[$answerArray[0]]

$_POST[$answerArray[1]]

:

$_POST[$answerArray[9]]

 

 

Is this correct??

 

 

Here is where I am getting mixed up...

 

Based on this code, it looks like $_POST is empty UNTIL we populate it here...

if (isset($_POST)){
$answerArray=array();
foreach($_POST['answerArray'] as $k =>$v){
$answerArray[$k]=trim($v);
}
}

 

 

Not sure if you follow where I am getting confused?!  :-[

 

Thanks,

 

 

Debbie

 

Link to comment
Share on other sites

I will try my best...

 

<textarea id="question1" name="answerArray[0]" 



To me, it looks sorta like I am creating an Array here?!   

Yes, by adding brackets to a name field in a form you are creating an array.  At this point it is a $_POST array.  And in your case you are also assigning the Key for each posted answerArray.

 

And what happens when the User types "I want to run my own business because..." in the first Form Field?

...and submits the form... we process creating a php array called answerArray.  These are the values you are echoing in your form.

 

Doesn't that erase what we did in the Form above?

No.  The form names are hard coded and it's what will be POSTed and if you didn't echo the php array value inside the form, the value would still be empty when posting again, even though we make an array called answerArray when processing.

 

If the fact that the names of the form array and php array are the same is hard to grasp, you could always change one of them but I see no need to as they're in a different format, html, php.

 

$_POST['answerArray'] is an array containing the keys and values from the form.  The foreach statement is taking this posted array and creating a php array called answerArray that you can then echo in your form or process to DB etc.

 

OK Debbie.

 

Based on your code.

if ($_SERVER['REQUEST_METHOD']=='POST'){

Should replace what I have

if (isset($_POST)){

 

So the trigger for processing should have been what you had.

 

if ($_SERVER['REQUEST_METHOD']=='POST'){
$answerArray=array();
foreach($_POST['answerArray'] as $k =>$v){
$answerArray[$k]=trim($v);
}
}

 

$_POST[$answerArray[0]]

$_POST[$answerArray[1]]

:

$_POST[$answerArray[9]]

 

 

Is this correct??

 

 

Here is where I am getting mixed up...

 

Based on this code, it looks like $_POST is empty UNTIL we populate it here...

Code: [select]

 

if (isset($_POST)){

$answerArray=array();

foreach($_POST['answerArray'] as $k =>$v){

$answerArray[$k]=trim($v);

}

}

 

 

 

Not sure if you follow where I am getting confused?!  :-[

 

foreach() is used to get the Key and Value from an array.  $_POST['answerArray'] is the array being passed by your form.

Each Key has a corresponding Value and so $_POST['answerArray'][9] will hold the value for answer nine etc.

 

Not sure how else to explain this.

Link to comment
Share on other sites

Drummin,

 

Be patient - I think we are making progress.  8)

 

 

I will try my best...

 

$_POST['answerArray'] is an array containing the keys and values from the form.

 

How does HTML know that is an array and not a single value?

 

That is what is probably throwing me off the most?!

 

Since $_POST is already an array, I figure things would look like...

$_POST['answerArray()']

 

or

 

$_POST['answerArray[]']

 

or whatever...

 

 

<textarea id="question1" name="answerArray[0]" 

 

To me, it looks sorta like I am creating an Array here?!  :confused:

 

Yes, by adding brackets to a name field in a form you are creating an array.  At this point it is a $_POST array.  And in your case you are also assigning the Key for each posted answerArray.

 

So if I wanted to access one of the elements in the SUB-array called 'answerArray' inside the PARENT array called '$_POST' how would I do that?

 

In other words, without using a ForEach, what would be the syntax to reference, say, field #7?

 

 

If the fact that the names of the form array and php array are the same is hard to grasp, you could always change one of them but I see no need to as they're in a different format, html, php.

 

So in this line of code...

	<textarea id="question1" name="answerArray[0]" cols="60" rows="8"><?php if (isset($answerArray[0])){echo htmlentities($answerArray[0], ENT_QUOTES);} ?></textarea>

 

 

name="answerArray[0]" is a SUB-array in the PARENT array of $_POST[], right?

 

 

And my sticky form is using the PHP array called $answerArray[0], right?

 

 

And these are completely different arrays, right??

 

Thanks,

 

 

Debbie

 

Link to comment
Share on other sites

Post in this case is a multidimensional array.  Just using your two example textareas and a submit field you would see.

Array
(
    [answerArray] => Array
        (
            [0] => 
            [1] => 
        )

    [submit] => Submit
)

Where the primary keys under $_POST are "answerArray" and "submit".  Youll see that [answerArray] is also an array with the keys (and any value).

So to back up a bit, An array has keys and values.

$array=Array(
[0]=>Value of Key 0,
[1]=>Value of Key 1,
);

 

If you have a simple form with input for name as an example.

<input type="text" name="Name" />

Then $_POST['Name'] will be the value entered in this field.

 

If however you placed [] after this name then you create an array called "Name".

<input type="text" name="Name[]" />

 

Now even undefined keys in the form will be defined when the code is processed, so let's say you want to enter a bunch of names and say your form has three of these fields.

<input type="text" name="Name[]" />
<input type="text" name="Name[]" />
<input type="text" name="Name[]" />

When keys are not defined in an array they start with  zero.

$_POST['Name']=Array(
[0]=>Value of Key 0,
[1]=>Value of Key 1,
[2]=>Value of Key 2,

 

Now you can access any array value by it's key.

$_POST['Name'][0]=Value of Key 0

OR

$_POST['answerArray'][7]=Value of Key 7

 

Remember though that it's the key you define in the form that defines the corresponding results

<textarea id="question7" name="answerArray[7]"> 

 

So in other words $_POST['primaryKey'].  If $_POST['primaryKey'] is also an array, you can access the value by the key

$_POST['primaryKey'][0].

 

 

Link to comment
Share on other sites

Another useful example of arrays is when dealing with products, ether when editing product names or setting quantity for a checkout for example.  This can be looped in your form.

<input type="hidden" name="productid[]" value="<?php echo $productid ?>" />
<input type="text" name="quantity[]" />

Then you do that same type of foreach statement and because keys are NOT defined in your form, they will start with zero and go up with each record.

 

foreach ($_POST[productid] as $k => $id){
$quantity=$_POST[quantity][$k];
echo "Product id: $id  Quantity: $quantity<br />";
//Replace with INSERT to DB or whatever  
}

Link to comment
Share on other sites

Drummin,

 

What shows up in $_POST when a Form is submitted?

 

If my Form has 10 Fields, and a User only completes 3 Fields, what will my $_POST array hold?

 

I ask this because I am trying to figure out the proper way to code things.

 

What I am working on is this...

 

In a User's profile, I have 10 Questions about Small Business.  But on the back-end I have 3 tables that form a many-to-many relationship...

 

member -||--------0<- bio_answer ->0-----------||- bio_question

 

What makes what I am working on TRICKY, is that one Form represents 10 records (versus one record in a more denormalized database).  And so when a User submits the "Thoughts" form, I have to loop through each Question and determine whether or not the Questions has been answered (i.e. Is there a record in the "bio_answer" table?)

 

So I am not sure if I should be checking every field, or just check the fields where the User either Added comments or Updated comments??  :shrug:

 

Actually, the more I think about it, I don't want to overwrite existing data with the same value because that would give me a misleading "updated_on" field...

 

Make sense?

 

 

Debbie

 

Link to comment
Share on other sites

If my Form has 10 Fields, and a User only completes 3 Fields, what will my $_POST array hold?

 

Just the three fields the user complets.

 

So I am not sure if I should be checking every field, or just check the fields where the User either Added comments or Updated comments??

 

You'll just need to check the post data, not each and every field.

 

If your update query is based on what post data is received you can avoid updating unmodified fields with their same value.

Link to comment
Share on other sites

If my Form has 10 Fields, and a User only completes 3 Fields, what will my $_POST array hold?

 

Just the three fields the user complets.

 

So I am not sure if I should be checking every field, or just check the fields where the User either Added comments or Updated comments??

 

You'll just need to check the post data, not each and every field.

 

If your update query is based on what post data is received you can avoid updating unmodified fields with their same value.

 

The more I think about this, the more complex things get...

 

Based on what you are saying above, if I display a new blank Form with my 10 Questions, the $_POST is empty, right?

 

And if the User types in Answers for Questions #1, 3, and 5, then my $_POST array would hold values in just #1, 3, and 5, right?

 

But here is where things get tricky...  (Or is that "Sticky"?!)  ;)

 

My Form is "sticky", so when the Form reloads, there will still be Answers #1, 3, and 5.  However, if a User types in a new response to Question #4, then my script should only do an INSERT on Answer #4 and NOT do an UPDATE over Answers #1, 3, and 5 which have not changed...

 

So how do I easily determine on the reloaded Form that only Answer #4 is new and needs to be INSERTED??

 

(I don't know why I didn't just stick all 10 Answers into ONE Record?!)  ::)

 

 

Debbie

 

Link to comment
Share on other sites

Hi Debbie, This sample should get you going.  Remember those array keys?  Used a lot of them here.  Hope it works for you.

<?php 
//establish DB connection
require("connection.php");
session_start();
//This is only an example based on what I know.  Change tables, fields and query style to fit your needs. 

//I will assume you have session already set for a memberid.
$memberid=$_SESSION['member_id'];
//Set if allowing members to update records
$canupdate="true";//false 

$errors=array();

if ($_SERVER['REQUEST_METHOD']=='POST'){
foreach($_POST['answerArray'] as $k =>$v){
	//trim value
	$response=trim($v); 
	//if not empty continue
	if (!empty($response)){
	 	//see if question already answered
		if (!empty($_SESSION['answerArray'][$k])){
			//if allowing update continue
			if ($canupdate=="true"){
				//See if post is different than already recorded
				if ($response!=$_SESSION['answerArray'][$k]){
				$response=mysql_real_escape_string($response);
				$qry="UPDATE bio_answer SET response='$response' WHERE
				question_id='$k' AND member_id='$memberid'"; 
				mysql_query($qry) or trigger_error($qry . ' has encountered and error<br />' . mysql_error());
				}//if ($response!=$_SESSION['answerArray'][$k])
			}//if ($canupdate=="true")
		}//if (!empty($_SESSION['answerArray'][$k]))
		else{ 
		$response=mysql_real_escape_string($response);
		$qry="INSERT INTO bio_answer (question_id,member_id,response) VALUES('$k','$memberid','$response')";  
		mysql_query($qry) or trigger_error($qry . ' has encountered and error<br />' . mysql_error());
		}//if (!empty($_SESSION['answerArray'][$k]))else
	}//if (!empty($response))
	else{
	$errors[$k]="Please enter your response to question $k.";
	}
}//foreach($_POST['answerArray'] as $k =>$v)
}//if ($_SERVER['REQUEST_METHOD']=='POST')

//Want answers available at processing to compare to posted value, so I set both questions and answers to session.
$_SESSION['questionArray']=array();
$_SESSION['answerArray']=array();

$sql = "SELECT bio_answer.response, bio_question.question_copy, bio_question.id, bio_answer.question_id ".
"FROM bio_question LEFT JOIN bio_answer ".
"ON bio_answer.question_id=bio_question.id AND bio_answer.member_id='$memberid'";
$result=mysql_query($sql);
while($row = mysql_fetch_array($result)){
$_SESSION['questionArray'][$row[2]]=$row[1];
$_SESSION['answerArray'][$row[2]]=$row[0];
}
?>
<html>
<body>
<?php
$bio_data=""; 
$bio_data.='<form action="" method="post">';
foreach($_SESSION['questionArray'] as $key => $value){
$bio_data.="<!-- Question $key -->
<label for=\"question$key\">$key.) $value</label><br />";
if (isset($errors[$key])){
$bio_data.='<span class="error">' . $errors[$key] . '</span><br />';		}
$bio_data.="<textarea id=\"question$key\" name=\"answerArray[$key]\" cols=\"60\" rows=\"8\">";
if (isset($_SESSION['answerArray'][$key])){$bio_data.=htmlentities($_SESSION['answerArray'][$key], ENT_QUOTES);} $bio_data.="</textarea>";
$bio_data.='<br />';
}//foreach($_SESSION['questionArray'] as $key => $value)
$bio_data.='<input type="submit" name="submit" value="Submit" />
</form>';

echo "$bio_data";
?>
</body>
</html>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.