I have an html form where I am grouping inputs using name="array[]" then just looping through the array with PHP when submitted. Well I am using array[] to store the question, but when the question (array index) is longer than 64 characters then It will not pass that array key to my PHP.
HTML
<textarea name="corporate[CAN YOU SHOW US SIMILAR PROJECTS WITH THE SAME TARGET AUDIENCE? COMPETITORS?]"></textarea>
When I do:
var_dump($_POST['array']);
I get array(0)
But when I use a shorter index, it works.
Now if I manually create an associative array it works fine:
$array = array("CAN YOU SHOW US SIMILAR PROJECTS WITH THE SAME TARGET AUDIENCE? COMPETITORS?"=>"0");
What am I doing wrong?
I think it has to be a problem with going from the html form to the PHP. I am trying to loop through the inputs with my PHP so that I can loop through and display each question and corresponding answer with:
foreach ($array as $key=>$value) {
if ($value != NULL) {
echo '<strong>' . $key . '</strong><br/>';
echo $value . '<br/><br/>';
}
}
Which gives me:
Question
Answer
Question
Answer
etc.
How else could I do this without giving each input their own name to pass the question, or hard coding the question in my HTML?
It might be because you're doing this
var_dump($_POST['array']);
when you named the textarea "corporate". Try just doing
var_dump($_POST);
You can use a hidden input with the question and match up the indexes with the answer:
<input type="hidden" name="question[1]" value="CAN YOU SHOW US BLAH?">
<textarea name="answer[1]"></textarea>
I assume you are dynamically adding the question text? If so you should probably use htmlentities on it to avoid issues.
Then just loop one and access the other:
foreach ($_POST['answer'] as $key => $value) {
if (!empty($value)) {
echo '<strong>' . $_POST['question'][$key] . '</strong><br/>';
echo $value . '<br/><br/>';
}
}
Related
PLEASE NOTE BEFORE READING:
Im making use of wordpress, divi and sportspress
Im trying to loop through these JSON strings and output them on my profile page (wordpress post)
Php code are added to posts with this plugin: Plugin Page
Im pulling JSON strings via an API(no problems encountered - only mentioning this here)
Im aware that there are similar questions, however, this is wordpress related and the answer could be either a solution for a WORDPRESS post OR a different implementation suggestion that might be more fitting for this CMS. This means im willing to change the methods used to output these strings :)
The JSON string:
{"name":"MaartenPAC","level":30}
Im trying to output the JSON string inside a wordpress post with the following code:
// Loop through Array
$profile1Array = {"name":"MaartenPAC","level":30}; // This is the PHP Array
foreach ($profile1Array as $key => $value) {
echo $value["name"] . ", " . $value["level"] . "<br>";
}
The Problem:
Im getting no output at all.I'm not sure if this is a syntax error perhaps? The plugin takes the php code above and generates a shortcode that can be pasted inside a post (one can think of it as a "php include" I guess?). Im still looking into this myself and will keep this question updated.
The main reason you are getting no output with the above code is syntax error, and most likely, you do not have PHP Errors enabled for output.
Either, check your servers log file, or enable error output.
One of the main issues is your definition of a array:
$profile1Array = {"name":"MaartenPAC","level":30};
This is not a valid syntax to define an array in PHP. This should look like:
$profile1Array = ["name" => "MaartenPAC", "level" => 30];
Second, your foreach statement is wrong. Since you are doing $key => $value, the $key would be 'name', and the $value would be 'MaartenPAC'.
This should look like:
foreach( $profile1Array AS $key => $value ) {
echo $key . ' is: ' . $level;
}
EDIT:
If it is so that you are getting an array as JSON string looking like {"name":"MaartenPAC","level":30} then you need to make use of the PHP function json_decode
The following loop works like a charm along with the plugin mentioned.
$array = json_decode('[{"name":"MaartenPAC","level":30}]');
foreach ($array as $key => $jsons) {
foreach($jsons as $key => $value) {
if($key == 'name'){
echo "Username is " . $value;
}
}
}
Output:
Username is MaartenPAC
I am trying to organize an array of data to be sent in an email. I have no problem getting the data, but I am not sure how to organize it.
Foreach: Here outputs a list of questions generated by the user in the backend
$message = array();
foreach($questions['questions'] as $key => $value){
if(is_array($value) && isset($value[ 'questionlist'])){
foreach($value as $key => $subquestion){ //line 119
foreach ($subquestion as $key => $value){
$message[] = $value['a-question'];
}
}
}
}
I am trying to conjoin the data with each other, the data from the foreach and the $_POST data which is check values.
My logic for doing it this way is because one comes from the database, one is just form data (that does not need to be saved to the database it comes from the front end unlike the data from the database that is generated via backend) That said there perhaps is a better way, but I pretty much got this I am just not sure how to join the data so it looks like
<li>MYARRAYDATA - MYFORMDATA</li>
<li>MYARRAYDATA - MYFORMDATA</li>
<li>MYARRAYDATA - MYFORMDATA</li>
//The form input data '0', '1' values
$checks = $_POST['personalization_result'];
//Putting that data into array_values
$checkValues = array_values($checks);
//Then passing the array_values into 'implode' and organizing it with a list (<li>)
$checkString = '<li>'.implode('</li><li>',$checkValues).'</li>';
//Then testing with var_dump outputs a nice list of '0','1' values
var_dump ($checkString);
Trying the same method but trying to conjoin the foreach array and the check values does not work, here is an example.
//Similar to $checkValues I pass the data from the foreach into "array_values"
var_dumping this works fine.
$arrayValues = array_values($message);
//This is obvious it's the same as above it "implodes" the data nicely into a list(<li>)
$arrayString = '<li>'.implode('</li><li>',$arrayValues).'</li>';
//This var dumps the "$arrayString" nicely
var_dump ($arrayString)
Again the actual question is here, how do I conjoin each piece of data?
My Attempts: Here are my attempts for "conjoining" the data.
// This does not work well (maybe by cleaning up it can work) but it outputs 2 separate lists
var_dump ($arrayString.'_'.$checkString);
//I tried to run it inside one implode variable this is invalid arguments
$checkString = '<li>'.implode('</li><li>',$arrayValues.'_'.$checkValues).'</li>';
//Modified one implode variable this outputs see below
$checkString = '<li>'.implode('</li>'.$arrayValues.'<li>',$checkValues).'</li>';
<li>Array
1</li>
<li>Array
0</li>
<li>Array
1</li>
<li>Array
0</li>
var_dump results: Here is the var_dump result of each array, I want to combine these into one list
$_POST array
// Var dump of form $_POST DATA
var_dump ($checkString);
//Result
1 //This is generated through the $_POST method not on database
0 //This is generated through the $_POST method not on database
1 //This is generated through the $_POST method not on database
0 //This is generated through the $_POST method not on database
DATABASE array
// Var dump of datbase generated from backend
var_dump ($arrayString);
//Result
I am 1 //This is generated in the backend and is stored on a database
Hi I am 2 //This is generated in the backend and is stored on a database
civil is 3 //This is generated in the backend and is stored on a database
THIS IS FOURTA //This is generated in the backend and is stored on a database
The Goal
I am 1 - 1 //This is checked
Hi I am 2 - 0 //This is NOT checked
civil is 3 - 1 //This is checked
THIS IS FOURTA - 0 //This is NOT checked
The Answer: Thanks to #xdim222
I didn't understand it at first, because of the increment, but now I understand it all, initially it would have worked but my variables were under the foreach statement and that was causing it not to return the array.
At least in my opinion thats what it was, because when I added the variable above the foreach it worked.
I modified the answer to suit my code.
//$messages = array('test1', 'test2', 'test3', 'test4', 'test5');
//Instead of using this array I used the array generated in my foreach above.
// Instead of this $checks = array(1,0,1,0); I take the $_POST value which generates an array, you can see above.
$checkValues = array_values($checks);
$checkString = implode($checkValues);
$i=0;
foreach($messages as $msg) {
echo $msg . ' - ' . ( isset($checkString[$i])? $checkString[$i] : 0 ) . '<br>';
$i++;
}
Again thanks to #xdim222 for being patient, reading my long question, and most importantly helping me learn, by asking this question and finding a solution this stuff really sticks and is in my opinion the best way to learn (by asking). :)
To make it easier, I assign $messages and $checks directly, I have tried this code and it works. You might have different elements of your arrays, but I think you can figure it out from my code below:
$messages = array('test1', 'test2', 'test3', 'test4', 'test5');
$checks = array(1,0,1,0);
$i=0;
foreach($messages as $msg) {
echo $msg . ' - ' . ( isset($checks[$i])? $checks[$i] : 0 ) . '<br>';
$i++;
}
PS: I made a mistake in my previous answer by incrementing $i before echoing things out, array element should start by 0.
While waiting for your reply to my comment above, I'm trying to write some code here..
I assume you want to display the questions that were pulled from database and it should be displayed based on what user chose in the form. So you may use this code:
foreach($questions['questions'] as $key => $value){
if(is_array($value) && isset($value[ 'questionlist'])){
foreach($value as $key => $subquestion){ //line 119
foreach ($subquestion as $key => $value){
$message[$key] = $value['a-question'];
}
}
}
}
I added $key in $message in the code above, with an assumption that $key is the index of a question, and this index will be matched with what user chose in the form. Then we can list all the questions that a user have chosen:
foreach($checks as $check)
echo '<li>'.$check . ' - ' . $message[$check].'</li>';
Is this what you want?
Based on your update:
$i=0;
foreach($message as $msg) {
$i++;
echo '<li>'. $msg . ' - ' . ( isset($checks[$i])? $checks[$i] : 0 ) . '</li>';
}
Maybe this is what you want.
As I said, there should be a relation between the $message and $checks, otherwise the above code looks a bit weird, because how do we know that a question is selected by user? Maybe you should show how you get that $_POST['personalization_result'] in your HTML.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP $_POST print variable name along with value
I have a form (whatever number of fields).. this form will send $_POST data.. I want to return every $_POST variable value and name.
I wanna do soemthing like this :
foreach($_POST as $field){
//****some code*****//
}
in a way that will display the fields and values like this:
name : Simo Taqi email : example#ymail.com
in other words :
if I have a post variable : $_POST['city']='las vegas'
I want to know how to get the name of the variable : 'city'.
$_POST is populated as an associative array, so you can just do this:
foreach ($_POST as $name => $val)
{
echo htmlspecialchars($name . ': ' . $val) . "\n";
}
Additionally, if you're just interested in the field names, you can use array_keys($_POST); to return an array of all the keys used in $_POST. You can use those keys to reference values in $_POST.
foreach (array_keys($_POST) as $field)
{
echo $_POST[$field];
}
foreach documentation
array_keys documentation
Use the extended foreach syntax:
foreach ($_POST as $key => $value)
{
echo $key . ": ". $value . "\n";
}
I disagree with this post, since it assumes that output is always intended for a browser. One should not get into the habit of this. \n is the correct usage and can be easily converted before output ( to a browser ) using the nl2br() function.
So I need to make new survey forms that are huge and I'm getting questions from db and adding them to array before printing.
Type of input also comes from array.
For example getting text inputs done like this:
if ($type == 'text'){//text input
$Line[] .= "<tr><td><input type='text' name='question_$q_id' $attributes class='$classes' value=\"";
$Line[] .= '<?php if (isset($_POST[\"question_$q_id\"])){echo $_POST[\"question_$q_id\"];}?>';
$Line[] .= "\"></td></tr>\n";
So the problem is of course is if isset php part. When done like this it simply makes a string value with php code in it.
Which way should I go about to have add php code as php code?
I retrieve values into the form simply like this:
foreach ( $Line as $q_id => $line ) {
echo "$line";
I did try the eval function but it gives me an error - I'm not sure how to properly use it.
Any form I used before I had all the elements added up simply by using "echo" in the loop, but it seems like creating and filling up an array with questions and then retrieving it makes more sense, however making field values sticky is the problem for me.
Is there an easy way to fix it, or should I just get back to echoing elements in the fetch loop?
if ($type == 'text'){//text input
$Line[] .= "<tr><td><input type='text' name='question_{$q_id}' {$attributes} class='{$classes}' value=\"";
if (isset($_POST["question_{$q_id}"]))
$Line[] .= $_POST["question_{$q_id}"];
$Line[] .= "\"></td></tr>\n";
}
In fact, a better way would to be:
if ($type == 'text'){//text input
$Line[] .= "<tr><td><input type='text' name='question_{$q_id}' {$attributes} class='{$classes}' value=\"".isset($_POST["question_{$q_id}"])?$_POST["question_{$q_id}"]:null."\"></td></tr>\n";
}
I've been working on trying to write a function that will grab the POST values of any given form submission, pop them into an array, loop through the array using trim, addslashes etcetera pass that value back to a variable where it can then be passed to a database.
Now the hurdle I have atm is getting all the input,textarea,select element data into an array upon form submission. code I have follows
$fields = array($_POST['1'], $_POST['2']);
$i = 0;
foreach ($fields as $field) {
$i++;
${'field'.$i } = trim(addslashes(strip_tags($field)));
echo "POST field info #". $i ." - ". ${'field'.$i }."<br />";
}
As you can see everything is fine here baring that the POST value names are still being in-putted statically, what I need is a way to get that POST data fed into a loop which dynamically calls the POST name using an increment variable and then pop all that data into the same array. Code I have tried follows.
for ($ii=0;$ii++;) {
foreach($_POST['$ii'] as $field) {
$fields = array($field);
}
}
$i = 0;
foreach ($fields as $field) {
$i++;
${'field'.$i } = trim(addslashes(strip_tags($field)));
echo "POST field info #". $i ." - ". ${'field'.$i }."<br />";
}
Now I know this wont work but I can sense I am relatively close, so I am wondering if any clever person can help me sort the last part out? I sadly am now going to sleep and wont be viewing this post for at least 9 hours, apologies.
Thanks in advance.
Dan.
$arrayOfPostValues = $_POST; // it already is an array
$arrayOfPostValues = array_map('strip_tags', $arrayOfPostValues);
$arrayOfPostValues = array_map('trim', $arrayOfPostValues);
Or, if you really, really want to use a loop:
foreach ($arrayOfPostValues as &$value) {
$value = trim(striptags($value));
}
I'd absolutely advise against the use of addslashes, it serves very little purpose. Use mysql_real_escape_string or prepared statements instead.
I'd also advise against breaking the vales out of the array into separate variables, it can only cause problems. If you really want to do it, there's the extract function, which does exactly that. But, again, don't do it. Arrays are the perfect way to handle this kind of data.
You need to assign values to $_POST[1] and $_POST[2] to begin with, I've done this for you but normally they would be populated from a form I assume?
I'm not sure why you want to do this sort of thing: ${'field'.$key}, but I've left that part as is as I assume you must have a reason.
Anyway I've modified your code a bit, see below.
$_POST['1'] = '<h1>variable 1</h1>';
$_POST['2'] = '<h2>variable 2</h2>';
foreach($_POST as $key => $value){
${'field'.$key} = trim(addslashes(strip_tags($value)));
echo "POST field info #". $key ." = ". ${'field'.$key}."<br />";
}
The above code outputs:
POST field info #1 = variable 1
POST field info #2 = variable 2
On a side note, using field names such as '1' and '2' is not very good. Try using something more descriptive but as I said above I assume you have a reason for doing this.
UPDATE:
You can still get this to work for any form even if you are using specific names for the form elements. I have added a few lines below as an example for you.
$_POST['email'] = 'example#example.com';
$_POST['password'] = 'hgbks78db';
$_POST['name'] = '';
foreach($_POST as $key => $value){
if($value==''){
echo 'POST field "'.$key . '" is empty<br />';
/* I added the name of the field that is empty to an error array
so you have a way of storing all blank fields */
$a_error[] = $key;
}
else{
echo 'POST field "'.$key . '" is not empty<br />';
}
}