Associative array from form inputs - php

I'm building a calculator for a mmo guild. At this moment I'm looking for a way to make data more easy to access for calcules.
Basically, I have a form with 5 text fields (just for test, there will be a lot more), and a select list (for choose the proper equation).
Example code:
<input type="text" id="strength" name="strength" value="0">
<input type="text" id="dexterity" name="dexterity" value="0">
<select name="equation" id="equation">
<option name="damage" id="damage">Damage</option>
<option name="defense" id="defense">Defense</option>
</select>
So this form will be procesed through a php file.
<form action="file.php" method="post">
//inputs here
<input type="submit" value="calculate">
</form>
At this moment I'm receiving all data in php file with vars:
$strength = (int)$_POST['strength'];
$dexterity = (int)$_POST['dexterity'];
For start is ok, but when my script is complete there will be more than 20 fields... so I wanna store all data in an array, something like this:
$strength = array(
'fuerza' => 125,
'dexterity ' => 125,
//and more fields...
);
And use this data in various different functions for equations:
function equation1()
{
$damage = $stats['dexterity'] + $stats['strength'];
}
I have read several posts and tutorials about use name value from inputs for create an array somethin like this: name="name[]". But doesn't work for me how I want. This calculator will receive just 1 value for each "stat", and I need have all these values in an array so I can access them from different fuctions in my script.
Please ask me if my question is not clear, and sorry if my english is bad.
EDIT AFTER SOLVE
I let here my code after solve:
.html example:
<input type="text" id="strength" name="stats[strength]" value="0">
<input type="text" id="dexterity" name="stats[dexterity]" value="0">
<select name="operation" id="operation">
<option name="damage" id="damage">Damage</option>
<option name="defense" id="defense">Defense</option>
</select>
.php example:
function critOp($stat)
{
$result = $stat * 0.00725;
return $result;
}
switch($_POST['operation']){
case 'damage' :
$critical = critOp($_POST["stats"]["dexterity"]);
break;
//more case...

You can use brackets in the name field to direct PHP to stick them in an array. If you use [] it will form a numerical array, but you can specify an associative key in the brackets like [dexterity]
<input type="text" id="dexterity" name="strength[dexterity]" value="125">
<input type="text" id="fuerza" name="strength[fuerza]" value="125">
This will result in
$_POST['strength'] = array(
'dexterity' => 125,
'fuerza ' => 125,
);
Bonus points
You can continue to enforce integer values by using array_map:
$_POST['strength'] = array_map('intval', $_POST['strength']);
This will make sure all values are integers.

Related

no values in my string from an imploded post array? PHP

Started learning PHP today so forgive me for being a noob. I have a simple HTML form where the user inputs 4 strings and then submits.
HTML form
<html>
<head>
<title>EMS</title>
</head>
<body>
<h1>EMS - Add New Employees</h1>
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
<table>
<tr><td>Enter a NAME:</td><td> <input type="text" name="name"></td></tr>
<tr><td>Enter a PPSN:</td><td> <input type="text" name="ppsn"></td></tr>
<tr><td>Enter a PIN :</td><td> <input type="text" name="pin"></td></tr>
<tr><td>Enter a DOB:</td><td> <input type="text" name="dob"></td></tr>
<tr><td></td><td><input type="submit" value="Add New Employee" name="data_submitted"></td></tr>
</table>
</form>
</html>
I want to implode the 4 elements in the $_POST["data submitted"] array to a string.
PHP
<?php
if (isset($_POST['data_submitted'])){
$employee = implode(",",$_POST['data_submitted']);
echo "employee = ".$employee;
}
?>
Why is it that when I run the project, Input the 4 strings into the form and submit that there is nothing contained within the employee string when its outputed? There is however a value in the employee string when I just implode the $_POST array like so without 'data_submitted'.
$employee = implode(",",$_POST);
The output of the $employee string is now - employee = will,03044,0303,27/5/6,Add New Employee
It contains the name,pps,pin,dob and this ADD New Employee value?
How do I just get the $employee string to contain just the name,pps,pin and dob from the $POST_[data_submitted] array?
If you wish to implode the submitted data, then you need to refer to the specific items, as follows:
<?php
$clean = [];
if (isset($_POST['data_submitted'])){
// one way to deal with possibly tainted data
$clean['name'] = htmlentities($_POST['name']);
$clean['ppsn'] = htmlentities($_POST['ppsn']);
$clean['pin'] = htmlentities($_POST['pin']);
$clean['dob'] = htmlentites($_POST['dob']);
$employee = implode(",",$clean);
echo "employee = $employee";
}
Never use submitted data without first checking to make sure that it is safe to do so. You need to validate it. Since the OP doesn't specify what kind of data the named inputs "ppsn", "pin", "dob" pertain to, this example does a minimum of validation. Each input might require more or something different.
Whether you're new or familiar with PHP, it is a good idea to frequently read the online Manual.
First, you need to know that php will treat value in the format: value="value here" as string.
So, calling implode(",",$_POST['data_submitted']); will return Add New Employee as declared here: <input type="submit" value="Add New Employee" name="data_submitted">.
From your question:
How do I just get the $employee string to contain just the name, pps, pin and dob from the $_POST[data_submitted] array?
Solution
1. Unset the <code>$_POST['data_submitted']</code> index in the $_POST super global variable
2. Implode it
// Unset the $_POST['data_submitted'] index
$post_data = unset( $_POST['data_submitted'] );
// Format the post data now
$format_post_data = implode( ",", $post_data );
// Escape and display the formatted data
echo htmlentities( $format_post_data, ENT_QUOTES );

Array to String Conversion error in Codeigniter

Well I am Stuck some where here in Array conversion:
My Controller:
$username = $this->input->post('FirstName');
$countryval= $this->input->post('country');
var_dump($countryval);
My View:
<input type="text" name="FirstName" id="Name" >
<?php
foreach ($countryDetails as $row )
{
echo '<input id="country" type="checkbox" name="country[]" class="unique" value="'.$row->country_id.'">'.$row->country_name.'<br/>';
}
?>
<script>
$('input.unique').click(function() {
$('input.unique:checked').not(this).removeAttr('checked');
});
</script>
I am getting the value from checkbox in an array and I need to pass that value as a string further.
I am not able to convert value from array to string i.e if I var_dump($countryval) I get value in array ! Please Help. Thank you
That is because you have used "country[]" as the name in input field
Please try this incase you need a single value to be returned (Edit made here coz I put type="checkbox" instead of "radio".. I have corrected it) Trust radios for single values.
echo '<input id="country" type="radio" name="country" class="unique" value="'.$row->country_id.'">'.$row->country_name.'<br/>';
hope that helps
You need "country[ ]" as name only if it has multiple values. Eg., For a multiple select
<select name="country[]" multiple>
<option></option> <!-- Your options go here-->
</select>
You can use input-checkbox too.. But with your question, I believe you need just a single value to be returned.
Ok.. Now From Your comments I kind of get what you want. Here is my suggestion
1) When you are having multiple checkboxes with the same name, the values are sent as an array.
2) If you would need a single value at a time and definitely need a checkbox, You can make a radio look like a checkbox like this.
3) If you really want to proceed with your javascript allowing only one checkbox at a time, you can do this.
// Load the 'array' helper
$this->load->helper('array');
// Use the 'element' function to return an element from the array
$countryval = element('0', $this->input->post('country')); //should work
Have a try..!!

Assistance with understanding php urls

I'm looking at websites that use php and I seea[]=val1 instead ofb=val2. My question is why are there brackets in the url? What type of code would produce this effect?
Why Are the Brackets in the URL?
The brackets are in the url to indicate that val1 is to be assigned the next position in the array a. If you are confused about the blank part of the bracket, look at how php arrays work.
What Kind of Code Would Produce This?
As for the code that would create such a url, it could either be an explicit definition by the coder or some other script, or it could be somehow created by a form using the method="get" attribute.
Example:
To create this, you can define an array as the name of an input field like so:
<form method="get">
<input name="a[]" ... />
<input name="a[]" ... />
<input name="a[]" ... />
</form>
Or you can just make a link (the a tag) with this url:
Click Me!
To parse this url with PHP, you would use the $_GET variable to retrieve the values from the url:
<?php
$a = $_GET['a'];
$val1 = $a[0];
$val2 = $a[1];
$val3 = $a[2];
...
print_r($a);
?>
The printout of the print_r($a) statement would look like this (if you wrapped it in a <pre> tag):
Array (
a => Array (
0 => 'val1',
1 => 'val2',
2 => 'val3'
)
)
That is the syntax for appending a new element to an array. There should be dollar signs preceding each variable:
$a[] = $val1;
You would see input fields on the page before, like:
<input name="color[]" type="checkbox" value="red">
<input name="color[]" type="checkbox" value="blue">
<input name="color[]" type="checkbox" value="green">
wherein the user could select multiple responses and they would be available in the $color array in the $_GET (and URL) of the action page, showing up like you describe.
(Similarly it could also be hidden variables passed as an array that are not based on user input.)

PHP avoiding a long POST

This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}

Javascript mysql interface?

I am going back though a web-based document numbering system from few weeks ago. To sum it up, the user types in the project,class,base, and dash number (PPP-CCC-BBBB-DDD) then it is added to a mysql database. Now most doc numbers go in order according to revisions. IE: A document 1465-630-0001-000 becomes, after revision, 1465-630-0002-000.
The boss wants the system to automatically fill the input text box for the base number if it detects that the user is entering a revised doc. So if a user types in 1465 into the project field and 630 into the class field the system should autofill the base field with the next available number. In the previous example this would be 0002.
It needs to be able to search the database for the first two fields so that it can find the next available one. Is there anyway to do this using javascript or something? SO was really helpful with my last javascript question pertaining to this system.
heres an bit of my code if it helps:
` ?>
<div id='preview'></div>
<form id='item' action="submit.php?item=1" method="post">
Enter Title:<input type="text" name="title" size="20"><BR>
Choose Project Code:
<SELECT NAME="project">
<OPTION VALUE="">Project...
<?
$query = "SELECT * FROM project ORDER BY project asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['project']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Choose Class Code:
<SELECT NAME="class">
<OPTION VALUE="">Class...
<?
$query = "SELECT * FROM class ORDER BY class asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['class']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Assigned Base Number:<input type="text" name="base" size="20"><BR>
Enter Dash Number:<input type="text" name="dash" size="20"><BR>
Enter Comments:<input type="text" name="comment" size="40"><BR>
<input type="hidden" name="item" value="1"/> `
Just a simple html/php input form with the project and class code list generated from a database pertaining to each.
Thanks for any help-Thomas
Update:
So, you're going to need to make an AJAX call (see example in my comment below) to some PHP script that will retrieve the base value you want and then returns that to the AJAX request. Once the request gets a response, you can use that data to fill in the value the way I originally said...
On a side note, since the example I gave you is a jQuery AJAX function, you should probably check out how to use jQuery to select elements on the page, instead of using straight JS.
E.g. for getting by ID and replacing value:
$("#base").attr('value', valueFromAjaxCall);
How to change value with JS:
If you use PHP to get the base value you want to fill into the field, then you can fill the value in with:
var baseField = document.getElementsByName("base")[0];
baseField.value = <?=$baseValue?>;
The getElementsByName() call returns an array, which is why you have to index into the field you want. I would suggest giving your <input> an id so that you can use document.getElementById() instead. You would do something like:
<input type="text" id="base" size="20">
and the JS to get the input element would be:
var baseField = document.getElementById("base");
...therefore, no need to index, in case you named any fields with the same name.
**Not sure about the PHP syntax.
An ajax call on focus of the 3rd field firing back to the server the values of the first two fields?
first, you'll probably want to use jQuery since it has great support is easy to use and will feel familiar to someone used to PHP.
so include your jQuery javascript code that you can get from :
http://jquery.com/
then, assume a form that looks like:
{form}
<input type=text id='major' name='major' value=''>
{Or a select, your choice}
<input type=text id='minor' name='minor'>
{or a select again}
<input type=text id='sequence' name='sequence' onFocus='getNextSequence()'>
...
{/form}
in your head, have your javascript:
function getNextSequence(){
var major=$('#major').val();
var minor=$('#minor').val();
if(!major){
alert('Select a major version#');
$('#major').focus();
return(false);
}
if(!minor){
alert('Select a minor version#');
$('#minor').focus();
return(false);
}
$.getJSON('http://url.to.getnextNumber.php',
{major:major,minor:minor},
function(data){
if(!data.error){
$('sequence').val(data.nextSequence);
}else{
alert(data.error);
}
}
});
}
the jQuery getJSON call will make a call back to your URL with two $_POST variables, major and minor. do your query, save the result as $result=array('nextSequence'=>$x,'error'=>'false');
and convert it to JSON with echo json_encode($result);
don't include ANY headers or any other content in the output of that file, and jQuery will pull the correct value and insert it where it's supposed to bed

Categories