I have 2 pages in php. The 1st page includes a form which transimts data to the 2nd page. The form uses method=post. Data transmitted successfully in the 2nd page. I have the following code, which gets data and printing them using the code:
php?
var_dump($_POST);
foreach ($_POST as $key => $value) {
echo $value;
}
?>
All I want is to extract data from array and place them into variables, because I want to use these varaibles later in some if startments and mysql queries. Any idea how can i do this?
First, these really are basic PHP skills (or programming skills for that matter). Try to follow some tutorials or courses before attempting to write code in the "real world".
As long as you know the key for the value you want to store, this is how you do it:
$yourVariableName = $yourArray['yourKey']; // or just a number if the key is an int
You don't need for loops to do this.
EDIT
$kentroName = $_POST['kentro_name'];
$kentroSurName = $POST['kentro_surname'];
// And then the following six.
<?php
var_dump($_POST);
$array = array();
foreach ($_POST as $key => $value) {
echo $value;
$array[$key] = $value;
}
print_r($array);
?>
Related
i have made some random input names, because its a drag and drop page builder, so i can't guess, how much elements user will use, so i have created a random input names,
for that am using php foreach loop for $_POST requests. i have tried to make it encoded into json and then later save it into database. but it looks like something is wrong in my json.
Here are my html demo codes :
<input style="display:none;" name="DATA-BLOCK-A(some random string)">
<input style="display:none;" name="DATA-BLOCK-B(some random string)">
PS: A is for selecting element A, and B is for element B.
here is my PHP code :
if (isset($_POST)) {
//$arr = array();
foreach($_POST as $key => $value)
{
$arr = array($key => $value);
$encode = json_encode($arr);
echo $encode;
}
}
and Here is the result :
{"sortlist":"block[]=D5e3385b75a75d&block[]=K5e3385b85a75e&block[]=C5e3385b95a75f&block[]=F5e3385ba5a760"}{"save_cont_flag":"0"}{"DATA-block-D5e3385b75a75d":"0#TRANSP
<\/p>"}{"DATA-block-K5e3385b85a75e":"0#TRANSP20"}{"DATA-block-C5e3385b95a75f":"01#TRANSP0images\/250place.jpg\u00b8"}{"text-1573532276681":""}{"textarea-1573532278320":""}{"DATA-block-F5e3385ba5a760":"121212unundefined"}{"page_name":"123"}{"aff_link":""}{"pause_link":""}{"seo_title":""}{"fbook":""}{"seo_desc":""}{"seo_keywords":""}{"back_color":"#EEEEEE"}{"body_color":"#FFFFFF"}{"back_image":""}{"ty_font_color":"#000000"}{"ty_override":""}{"ty_name":"12314"}{"ty_stm":""}{"modal_para_width":"0"}{"catcha_url":""}{"catcha_un":"Yes"}{"catcha_message":""}{"code_head":""}{"code_body":""}{"modal_share_width":"0"}{"modal_cta_width":"0"}{"modal_video_width":"0"}{"modal_mp_width":"0"}{"modal_stm_width":"0"}{"modal_image_width":"0"}{"modal_bonus_width":"1"}{"ty_headline":""}{"modal_spacer_width":"0"}{"att_bar_status":"0"}{"att_delay_in":"0"}{"att_bar_color":"#bbbbbb"}{"att_gradient":"0"}{"att_text_color":"#000000"}{"att_text_font":"Open Sans:400"}{"att_text_size":"14"}{"att_bar_message":"Add Your Attention Bar Text Here"}{"att_link_color":"#000000"}{"att_link_label":"Add Link Text Here"}{"att_link_url":"http:\/\/commissiongorilla.com"}{"count_font":"Open Sans:800"}{"count_size":"55"}{"count_status":"0"}{"count_type":"0"}{"count_end":"01\/31\/2020 6:41 AM"}{"count_zone":"0.0"}{"count_eg_days":"0"}{"count_eg_hours":"0"}{"count_eg_mins":"0"}{"count_digit_color":"#bbbbbb"}{"count_label_color":"#bbbbbb"}{"count_background":"0"}{"count_language":"1"}{"count_exp":"0"}{"count_url":"http:\/\/commissiongorilla.com"}{"count_add_days":"0"}{"count_add_hours":"0"}{"count_add_mins":"0"}{"modal_countdown_width":"0"}{"modal_review_width":"0"}
and also how seperate all A BLOCKS and B BLOCKS?
Thanks.!
You don't need to use a loop.
Just used json_encode :
$json = json_encode($_POST);
If you need to get key contain DATA-block-, you can write :
foreach ($_POST as $key => $value) {
if (strpos($key, 'DATA-block-') !== false) {
// Here `DATA-block-{}`
}
}
If you change the input names to DATA-BLOCK-A[] and DATA-BLOCK-B[], $_POST['DATA-BLOCK-A'] will contain an array of all a blocks and $_POST['DATA-BLOCK-B'] will contain an array of all b blocks.
This also eliminates the need for generating random strings.
Usually when I use PHP I create a variable and post statement for each form input like so:
$myVar1 = $_POST["formItem1"];
$myVar2 = $_POST["formItem2"];
ect......
I know if i use:
echo $_POST;
I can get all the key and values from the form inputs but I don't know how to use them in a script.
So I guess I have 2 questions:
How do I quickly post all form inputs without creating a variable for each input?
How do I use a posted in a script without having it assigned to a specific variable?
To simply echo all the inputs, you can use a foreach loop:
foreach ($_POST as $key => $value) {
echo $value.'<br/>';
}
If you don't want to store them in variables, use arrays:
$data = array();
foreach ($_POST as $key => $value) {
$data[] = $value;
}
Now, $data is an array containing all the data in $_POST array. You can use it however you wish.
You don't have to assign to a variable. You can use directly $_POST['input_name']
If you want to deal with each sended params, you can use foreach loop:
foreach ($_POST as $key => $val)
{
echo "$key : $val <br/>";
}
for this instance of just quickly checking and testing i typically just use the print_r() function: documentation here
as quoted from the docs:
print_r() displays information about a variable in a way that's readable by humans.
one line easy to toggle on and off (with comments)- no need to use any form of variables
print_r($_POST);
if i need my output nice and readable i like to expand it as follows:
function print_r2($x){
echo '<pre>';
print_r($x);
echo '</pre>';
}
and then you can call with: print_r2($_POST);
this way you get the pre-formatted text block on your html page and can see the line breaks and tabbed spacing provided from the $_POST object printout
Another way to extract (besides the extract function) variables is;
$array = array('foo'); // Which POST variables do you want to get
foreach($array as $key) {
if(!isset(${$key})) { // Check if variable hasn't been assigned already
${$key} = $_POST[$key];
}
}
echo $foo;
I would not recommend it because it can get quite messy to keep up.
View everything in $_POST is useful for debugging
echo '<pre>'.print_r($_POST, true).'</pre>';
Access a specific checkbox
HTML
<input type="checkbox" value="something" name="ckbox[]" checked>
<input type="checkbox" value="anotherthing" name="ckbox[]" checked>
PHP
echo $_POST['ckbox'][0]; // something
echo $_POST['ckbox'][1]; // anotherthing
// isolate checkbox array
$ckbox_array = $_POST['ckbox'];
Define a function that allows you to access a specific $_POST item by name (key):
function get_post_value($name, $default)
{
if ( isset($_POST[$name]) ) {
return $_POST[$name];
} else if ( $default ) {
return $default;
}
return null;
}
$default allows you to pass a value that can be used as a fallback if the key you specify isn't present in the $_POST array.
Now you can reference $_POST items without assigning them to a variable, and without worrying if they are set. For example:
if ( get_post_value('user-login-submit', false) ) {
// attempt to log in user
}
You can use extract($_POST), it will create variables for you.
For example, you can have for the code you posted :
<?php
$_POST["formItem1"] = "foo";
extract($_POST);
echo $formItem1; // will display "foo"
?>
EDIT : it's not PHP explode, it's extract.
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.
I have form with changable content of textareas, from 1 to 5, each time with different names. I cannot modify the form itself.
how can i get number of textareas in form and names of them (it would be the best if i could do it clean in php without javascript).
the form is using method="POST" and PHP version is 5.2+
EDIT: i forgot to tell you that i have only textareas in form.
You could do something along the lines of :
$count=0;
$formElements=array();
foreach ($_POST as $key => $val)
{
$count++;
$formElements[]=$key;
}
echo "The form as $count elements.";
var_dump($formElements);
If you want the values of the post you could make a two dimensional array like this:
foreach ($_POST as $key => $val)
{
$count++;
$formElements[]=array($key => $val);
}
if you post form to php script, $_POST variable is array. then you can use something like this:
foreach($_POST as $v){} to get every field.
I have an HTML form being populated by a table of customer requests. The user reviews each request, sets an operation, and submits. The operation gets set into a POST arg as follow
$postArray = array_keys($_POST);
[1]=>Keep [2]=>Reject [3]=>Reject [4]=>Ignore ["item id"]=>"operation"
This is how I am parsing my POST args, it seems awkward, the unused $idx. I am new to PHP, is there a smoother way to do this?
$postArray = array_keys($_POST);
foreach($postArray as $idx => $itemId) {
$operation = $_POST[$itemId];
echo "$itemId $operation </br>";
// ...perform operation...
}
foreach ($_POST as $key => $value) // $key will contain the name of the array key
You could use
foreach($_POST as $itemId => $operation ) {
echo "$itemId $operation </br>";
// ...perform operation...
}
instead
http://nz.php.net/manual/en/control-structures.foreach.php
You don't have to use $idx in loop if is not needed.
It might be like that:
foreach($postArray as $itemId) {
...
}
Main problem is the data structure is very messy.
Maybe it's better way to organise form output.
Probably in some well structured associative array.
I can't see the form, I don't know the details so it's hard to tell more.