Collect specific fields to an array - php

Each div with the class "row" is added upon request from the user, to be able to add multiple items at once. So now is the question how I'll collect all the forms in to an array that PHP can read (like JSON for instance). I'll guess that there's already some easy and effective way of doing this?
<div class="container">
<div class="row">
<input type="text" name="value1" id="textfield" />
<input type="text" name="value2" id="textfield" />
<input type="text" name="value3" id="textfield" />
</div>
</div>
Here's what I would like to achieve out of the shown example:
array(
array ('value1' => '',
'value2' => '',
'value3' => '')
);
Thanks!
Update:
The form will be handled with PHP and it would be super to be able to do something like a foreach loop on the specific container-div content.

Give each 'group' of inputs the same name, then add square brackets to the end
<div class="container">
<div class="row">
<input type="text" name="value1[]" id="textfield" />
<input type="text" name="value2[]" id="textfield" />
<input type="text" name="value3[]" id="textfield" />
</div>
<div class="row">
<input type="text" name="value1[]" id="textfield" />
<input type="text" name="value2[]" id="textfield" />
<input type="text" name="value3[]" id="textfield" />
</div>
</div>
When you post the form, your php $_POST variable will then contain arrays for value1, value2 and value2:
var_dump($_POST); // array('value1' = array(...
You can then iterate through to 'regroup' the rows within PHP (but first, i'd change the field names to field1 etc rather than value1):
$rows = array(); // set up an empty array to hold your rows
// loop through each POST var
foreach($_POST AS $key=>$field) {
if(is_array($field)) {
foreach($field AS $rowIndex=>$fieldValue) {
$rows[$rowIndex][$field] = $fieldValue; // put the value in a the array by row, field
}
}
}
var_dump($rows);
This would give:
array(
[0] => array(
'field1' => 'value1',
'field2' => 'value2',
'field3' => 'value3'
),
[1] => array(
'field1' => 'value1',
'field2' => 'value2',
'field3' => 'value3'
),
...
)

<div class="container">
<div class="row">
<input type="text" name="value[0][value1]" class="textfield" />
<input type="text" name="value[0][value2]" class="textfield" />
<input type="text" name="value[0][value3]" class="textfield" />
</div>
<div class="row">
<input type="text" name="value[1][value1]" class="textfield" />
<input type="text" name="value[1][value2]" class="textfield" />
<input type="text" name="value[1][value3]" class="textfield" />
</div>
</div>
Changed id to class as reusing the same id is invalid HTML.

To convert XML to JSON you can try with:
Services_Json from PEAR: http://www.ibm.com/developerworks/xml/library/x-xml2jsonphp
the Zend_Json component of the Zend Framework: http://framework.zend.com/manual/en/zend.json.xml2json.html

Related

php create array with key by html input

am trying to create array with key by using html input
here's my html input
<form method="post" action="">
<input type="text" name="name[][you]" value="" />
<input type="text" name="name[][he]" value="" />
<input type="text" name="name[][she]" value="" />
<input type="text" name="name[][you]" value="" />
<input type="text" name="name[][he]" value="" />
<input type="text" name="name[][she]" value="" />
<button type="submit">go</button>
</form>
my outbut is
Array ( [0] => Array ( [you] => jhon ) [1] => Array ( [he] => joy ) [2] => Array ( [she] => sarah ) [3] => Array ( [you] => samm ) [4] => Array ( [he] => petter ) [5] => Array ( [she] => susan ) )
but i want the array to be like this
Array( [0]=> array ( [you] => jhon [he] => joy [she] => sarah )[1]=> array ( [you] => pitter [he] => tom [she] => suszan ) )
is there away to do that
try like this ==>
<form method="post" action="">
<input type="text" name="name[0][you]" value="" />
<input type="text" name="name[0][he]" value="" />
<input type="text" name="name[0][she]" value="" />
<input type="text" name="name[1][you]" value="" />
<input type="text" name="name[1][he]" value="" />
<input type="text" name="name[1][she]" value="" />
<button type="submit">go</button>
</form>
OR
<form method="post" action="">
<?php $n = 2; // how many interval you want
for ($i = 0; $i < $n; $i++) {
?>
<input type="text" name="name[<?php echo $i; ?>][you]" value="" />
<input type="text" name="name[<?php echo $i; ?>][he]" value="" />
<input type="text" name="name[<?php echo $i; ?>][she]" value="" />
<?php } ?>
</form>
If you want to output an array with two children then set the keys manually, name[0] for the first three inputs and name[1] for the last three.
Everytime you write name="[][key]" php increment automatic the key.
if you write syntax like [] php increment the index of array.
Small explation
For example:
If you write an array like this
$array[] = "msg1";
$array[] = "msg2";
$array[] = "msg3";
$array length will be 2 (3 elements because it starts from 0) and it is same as
$array[0] = "msg1";
$array[1] = "msg2";
$array[2] = "msg3";
This is different from above
$array[0] = "msg1";
$array[1] = "msg2";
$array[1] = "msg3";
This array will have only 1 length (2 elements only)
Solution of your question is :
<form method="post" action="">
<input type="text" name="name[0][you]" value="" />
<input type="text" name="name[0][he]" value="" />
<input type="text" name="name[0][she]" value="" />
<input type="text" name="name[1][you]" value="" />
<input type="text" name="name[1][he]" value="" />
<input type="text" name="name[1][she]" value="" />
<button type="submit">go</button>
</form>

INSERT INTO wp DB from input fields

I'm creating (and deleting) input fields dynamically in jQuery so they looks like:
<div id="new">
<div>
<input type="text" name="title1" value="" />
<input type="text" name="desc1" value="" />
</div>
<div>
<input type="text" name="title4" value="" />
<input type="text" name="desc4" value="" />
</div>
<div>
<input type="text" name="title7" value="" />
<input type="text" name="desc7" value="" />
</div>
</div>
As you can see, my fields names are not always like: 1,2,3 but they're sometimes like 1,4,7.
My php code (part) to insert row into db table:
$i = 0;
global $wpdb;
$table_name = $wpdb->prefix . 'plugin';
$wpdb->insert( $table_name, array( 'title' => $_POST['title'], 'desc' => $_POST['desc'] ) );
jQuery:
var count = <?php echo $i; ?>;
$("#addnewbutton").click(function() {
count = count + 1;
$('#new').append('<div><input type="text" name="title'+count+'" value="" /><input type="text" name="desc'+count+'" value="" /></div>');
});
I know that I need to use "for" loop (probably) but I don't know how to do it and I don't want to add empty rows.
Regards
Taking a purely PHP approach, you can run a loop through $_POST and check if the keys begin with 'title', split the string into two parts: the 'title' and the {number}. Check if a key with 'desc{number}' exists, if it does...you know what to do.
You can also process the form with JavaScript/JQuery first so it's really nice when PHP gets it by a JSON that has a 'title' obj and a 'desc' obj.

HTML Element Arrays - Multidimensional

I'm not 100% sure of the correct terminology of what I'm even asking, but I currently have a form that is being posted that has an array of elements:
<form>
<input type="text" name="album_songs[0][title]" value="Let It Go" />
<input type="text" name="album_songs[0][writer]" value="Robert Lopez, Kristen Anderson-Lopez" />
<input type="text" name="album_songs[0][composer]" value="Frozen" />
<input type="text" name="album_songs[0][length]" value="3:44" />
<input type="text" name="album_songs[0][genre]" value="Soundtrack, Music, Animated" />
<input type="text" name="album_songs[0][songorder]" value="5" />
<input type="text" name="album_songs[1][title]" value="Love Is An Open Door" />
<input type="text" name="album_songs[1][writer]" value="Robert Lopez" />
<input type="text" name="album_songs[1][composer]" value="Frozen" />
<input type="text" name="album_songs[1][length]" value="2:07" />
<input type="text" name="album_songs[1][genre]" value="Soundtrack, Music, Animated" />
<input type="text" name="album_songs[1][songorder]" value="4" />
</form>
And in my code, I can access these elements like the following:
$songs = $_POST["album_songs"];
foreach($songs as $song) {
$title = $song["title"];
$writer = $song["writer"]; // turn into array??
$composer = $song["composer"];
$length = $song["length"];
$genre = $song["genre"]; // turn into array??
$songorder = $song["songorder"];
}
What I would like to have happen, is not only have an array of songs, but also an array of Writers and Genres. Is this even possible? I tried mocking up something like the following but it did not work:
<input type="text" name="album_songs[4][genre[0]]" value="Soundtrack" />
<input type="text" name="album_songs[4][genre[1]]" value="Music" />
<input type="text" name="album_songs[4][genre[2]]" value="Animated" />
Any suggestions or is it even possible?
I might consider a dropdown, but you almost had it:
<input type="text" name="album_songs[4][genre][]" value="Soundtrack" />
<input type="text" name="album_songs[4][genre][]" value="Music" />
<input type="text" name="album_songs[4][genre][]" value="Animated" />
Gives this:
Array
(
[4] => Array
(
[genre] => Array
(
[0] => Soundtrack
[1] => Music
[2] => Animated
)
)
)
Try to use square bracket syntax to convert your form inputs into an array.
I.E. :
<input type="text" name="album_songs_title[]" value="Title1" />
<input type="text" name="album_songs_title[]" value="Title2" />
Then, you will be able to browse your datas with a foreach().
I think it might work.

CodeIgniter: When form data inserted to a table through an array, only "0" values are written in to the database

Everything is working fine except, instead of writing the data on the form, it writes zeros. The table (new_reservation) looks like this after submitting some values:
PK: res_id (AI, NN)
Not Null: All except "ext_bed"
Model: (reservations_model.php)
class Reservations_model extends CI_Model {
function add_reservations($data) {
$this->db->insert('new_reservation', $data);
return;
}
}
Controller: (reservations.php)
class Reservations extends CI_Controller {
function index() {
$this->load->view('/main/new_reservation');
$this->load->model('reservations_model');
}
function add_reservations() {
$data = array (
'room_type' => $this->input->post('room_type'),
'meal_type' => $this->input->post('meal_type'),
'bed_type' => $this->input->post('bed_type'),
'ext_beds' => $this->input->post('ext_beds'),
'number_of_guests' => $this->input->post('number_of_guests'),
'start_date' => $this->input->post('start_date'),
'end_date' => $this->input->post('end_date'),
'reservation_duration' => $this->input->post('reservation_duration'),
'room_number' => $this->input->post('room_number'),
'total' => $this->input->post('total')
);
$this->reservations_model->add_reservations($data);
$this->index();
}
}
View: (new_reservation.php in /views/main folder)
<?php echo form_open('reservations/add_reservations'); ?>
<p>
<label for="room_type">Room Type*: </label>
<select id="room_type"></select>
</p>
<p>
<label for="meal_type">Meal Type*: </label>
<select size="1" multiple="multiple" id="meal_type"></select>
</p>
<p>
<label for="bed_type">Bed Type*: </label>
<select id="bed_type"></select>
</p>
<p>
<label for="ext_beds">Extra Bed(s): </label>
<input type="text" id="ext_beds" />
</p>
<p>
<label for="number_of_guests">Number of Guests: </label>
<input type="text" id="number_of_guests" />
</p>
<p>
<label for="start_date">Check-in Date*: </label>
<input type="text" id="start_date" />
</p>
<p>
<label for="end_date">Checkout Date*: </label>
<input type="text" id="end_date" />
</p>
<p>
<label for="reservation_duration">Duration: </label>
<input type="text" id="reservation_duration" />(Nights)
</p>
<p>
<label for="room_number">Room Number: </label>
<input type="text" id="room_number" />
</p>
<p>
<label for="total">Total: </label>
<input type="text" disabled="disabled" id="total" readonly="readonly" />
</p>
<p>
<input class="btn" type="reset" />
<input class="btn btn-primary" type="submit" value="Check-in" />
</p>
<?php echo form_close(); ?>
In view
Use name not id
sample example from your code
<p>
<label for="start_date">Check-in Date*: </label>
<input type="text" id="start_date" name="start_date" />
</p>
Your form data.. they should have a name value ex:
<input type="text" id="end_date" name="end_data"/>
Use name along with id, eg:
<input type="text" id="number_of_guests" name="number_of_guests">
for all the input statements
get a value using name not by id
<input type="text" id="number_of_guests" name="number_of_guests">

Using the same script multiple times for one form (using PHP)

I am relatively new to PHP and programming, so please pardon my ignorance and language.
I have a form that has multiple instances of the same input fields (see below). I have a script that will process the input data, but only if it is submitted one set at a time(also below). I will like to have one submit button at the button of the form that would execute the script for however many multiples of the data set I have on the page.
Does anyone have any idea how I can get this to work? I cannot rename the variables (I tried that) because the receiving server needs the data labels to appear exactly as they are below. Any help/direction would be greatly appreciated. Thanks!
My form:
<form method="post" action="<?php echo (AUTHORIZENET_SANDBOX ? AuthorizeNetDPM::SANDBOX_URL : AuthorizeNetDPM::LIVE_URL)?>" id="checkout_form">
<?php
$time = time();
$fp_sequence = $time;
$fp = AuthorizeNetDPM::getFingerprint(AUTHORIZENET_API_LOGIN_ID, AUTHORIZENET_TRANSACTION_KEY, $amount, $fp_sequence, $time);
$sim = new AuthorizeNetSIM_Form(
array(
'x_amount' => $amount,
'x_fp_sequence' => $fp_sequence,
'x_fp_hash' => $fp,
'x_fp_timestamp' => $time,
'x_relay_response'=> "TRUE",
'x_relay_url' => $coffee_store_relay_url,
'x_login' => AUTHORIZENET_API_LOGIN_ID,
'x_test_request' => TEST_REQUEST,
)
);
echo $sim->getHiddenFieldString();
}
?>
<fieldset>
<H3>Card #1</H3>
<div>
<label>Amount</label>
<input type="text" class="text required" size="4" name="amount" value=""></input>
</div>
<div>
<label>Credit Card Number</label>
<input type="text" class="text required creditcard" size="15" name="x_card_num" value="6011000000000012"></input>
</div>
<div>
<label>Exp.</label>
<input type="text" class="text required" size="4" name="x_exp_date" value="04/15"></input>
</div>
<div>
<label>CCV</label>
<input type="text" class="text required" size="4" name="x_card_code" value="782"></input>
</div>
</fieldset>
<fieldset>
<div>
<label>First Name</label>
<input type="text" class="text required" size="15" name="x_first_name" value="John"></input>
</div>
<div>
<label>Last Name</label>
<input type="text" class="text required" size="14" name="x_last_name" value="Doe"></input>
</div>
</fieldset>
<fieldset>
<div>
<label>Address</label>
<input type="text" class="text required" size="26" name="x_address" value="123 Four Street"></input>
</div>
<div>
<label>City</label>
<input type="text" class="text required" size="15" name="x_city" value="San Francisco"></input>
</div>
</fieldset>
<fieldset>
<div>
<label>State</label>
<input type="text" class="text required" size="4" name="x_state" value="CA"></input>
</div>
<div>
<label>Zip Code</label>
<input type="text" class="text required" size="9" name="x_zip" value="94133"></input>
</div>
<div>
<label>Country</label>
<input type="text" class="text required" size="22" name="x_country" value="US"></input>
</div>
</fieldset>
<fieldset>
<H3>Card #2</H3>
<div>
<label>Amount</label>
<input type="text" class="text required" size="4" name="amount" value=""></input>
</div>
<div>
<label>Credit Card Number</label>
<input type="text" class="text required creditcard" size="15" name="x_card_num" value="6011000000000012"></input>
</div>
<div>
<label>Exp.</label>
<input type="text" class="text required" size="4" name="x_exp_date" value="04/15"></input>
</div>
<div>
<label>CCV</label>
<input type="text" class="text required" size="4" name="x_card_code" value="782"></input>
</div>
</fieldset>
<fieldset>
<div>
<label>First Name</label>
<input type="text" class="text required" size="15" name="x_first_name" value="John"></input>
</div>
<div>
<label>Last Name</label>
<input type="text" class="text required" size="14" name="x_last_name" value="Doe"></input>
</div>
</fieldset>
<fieldset>
<div>
<label>Address</label>
<input type="text" class="text required" size="26" name="x_address" value="123 Four Street"></input>
</div>
<div>
<label>City</label>
<input type="text" class="text required" size="15" name="x_city" value="San Francisco"></input>
</div>
</fieldset>
<fieldset>
<div>
<label>State</label>
<input type="text" class="text required" size="4" name="x_state" value="CA"></input>
</div>
<div>
<label>Zip Code</label>
<input type="text" class="text required" size="9" name="x_zip" value="94133"></input>
</div>
<div>
<label>Country</label>
<input type="text" class="text required" size="22" name="x_country" value="US"></input>
</div>
</fieldset>
<input type="submit" value="BUY" class="submit buy">
</form>
My script:
<?php
require_once 'coffee_store_settings.php';
if ($METHOD_TO_USE == "AIM") {
$transaction = new AuthorizeNetAIM;
$transaction->setSandbox(AUTHORIZENET_SANDBOX);
$transaction->setFields(
array(
'amount' => $amount,
'card_num' => $_POST['x_card_num'],
'exp_date' => $_POST['x_exp_date'],
'first_name' => $_POST['x_first_name'],
'last_name' => $_POST['x_last_name'],
'address' => $_POST['x_address'],
'city' => $_POST['x_city'],
'state' => $_POST['x_state'],
'country' => $_POST['x_country'],
'zip' => $_POST['x_zip'],
'email' => $_POST['x_email'],
'card_code' => $_POST['x_card_code'],
)
);
$response = $transaction->authorizeAndCapture();
if ($response->approved) {
// Transaction approved! Do your logic here.
header('Location: thank_you_page.php?transaction_id=' . $response->transaction_id);
} else {
header('Location: error_page.php?response_reason_code='.$response->response_reason_code.'&response_code='.$response->response_code.'&response_reason_text=' .$response->response_reason_text);
}
} elseif (count($_POST)) {
$response = new AuthorizeNetSIM;
if ($response->isAuthorizeNet()) {
if ($response->approved) {
// Transaction approved! Do your logic here.
// Redirect the user back to your site.
$return_url = $site_root . 'thank_you_page.php?transaction_id=' .$response->transaction_id;
} else {
// There was a problem. Do your logic here.
// Redirect the user back to your site.
$return_url = $site_root . 'error_page.php?response_reason_code='.$response->response_reason_code.'&response_code='.$response->response_code.'&response_reason_text=' .$response->response_reason_text;
}
echo AuthorizeNetDPM::getRelayResponseSnippet($return_url);
} else {
echo "MD5 Hash failed. Check to make sure your MD5 Setting matches the one in config.php";
}
}
PHP supports array notation for form fields, so you can force values to show up multiple times. e.g.
<input type="text" name="data[1]" value="foo" />
<input type="text" name="data[a]" value="bar" />
<input type="text" name="data[abcef]" value="baz" />
would give you a $_POST structure like:
$_POST['data'] = array(
0 => 'foo'
'a' => 'bar'
'abcef' => 'baz'
)
Since you'd have multiple copies of multiple fields, all requiring the data to be kept together, then structure your form like:
Set #1
<input name="somefield[1]" />
<input name="otherfield[1]" />
...
Set #2
<input name="somefield[2]" />
<input name="otherfield[2]" />
and then do this on the server upon submission:
foreach(array_keys($somefield) as $key) {
$somefield = $_POST['somefield'][$key];
$otherfield = $_POSt['otherfield'][$key];
... do something ...
}
You could add the form inputs in an array and use an foreach when you run the code.
<input type="text" class="text required" size="4" name="cards[0][amount]" value=""></input>
<input type="text" class="text required creditcard" size="15" name="cards[0][x_card_num]" value="6011000000000012"></input>
<input type="text" class="text required" size="4" name="cards[1][amount]" value=""></input>
<input type="text" class="text required creditcard" size="15" name="cards[1][x_card_num]" value="6011000000000012"></input>
etc etc etc.
You can get the results by doing
foreach($_POST['cards'] AS $c) {
echo $c['amount'];
}

Categories