Assistance with understanding php urls - php

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.)

Related

How can I put a POST inside another POST in PHP

I am trying to take the contents of a form and i want to display them using PHP. The way the form is structured is the following:
There is a list of checkboxes, which when they are clicked, a JavaScript function will create another <input> tag. The JS then sets the name of the new input to <input name="value of checkbox">.
What I need to do is get my PHP to take the value of the <input> I created.
Here is my HTML of the checkboxes.
<input name="product[]" value="value of Check 1" id="id-check-1" type="checkbox" onclick="id-check-1"/><input name="product[]" value="value of Check 2" id="id-check-2" type="checkbox" onclick="id-check-2"/><input name="product[]" value="value of Check 3" id="id-check-3" type="checkbox" onclick="id-check-3"/>
Here is my HTML of the inputs created by the JS.
<input name="value of Check 1" type="text"/><input name="value of Check 2" type="text"/><input name="value of Check 3" type="text"/>
PHP:
$aProduct = $_POST['product];
$product1 = $aProduct[0];
$product2 = $aProduct[1];
$product3 = $aProduct[2];
$input1 = $_POST[$product1];
$input2 = $_POST[$product3];
$input3 = $_POST[$product3];
I tried using this PHP to obtain the value inputted to the crated inputs. This shouldwork, since the name of the inputs = the value of the checkboxes, so in short, this is what I've done:$_POST[$_POST['product']]
Unfortunately, it doesnt work and the variables $input1, $input2 & $input3 dont return any value. So I'd like to know: A) Can i put a _POST within a _POST? and B) What can I do to make my code work?
First of alll the $_POST Variable is one Super Global in PHP i dont think it makes any sense to use $_POST[$_POST...
http://php.net/manual/en/language.variables.superglobals.php
Also i dont think you have to create extra inputs just use $_POST['product'] (array of values which are selected)
try var_dump($_POST['product']) to see whats stored in it
If I understand correctly otherwise guide me in the right direction.
First: You have given the name product[]. Then it should be $_POST['product[]'] which I don't know if that is possible.
Second: If you are writing the value of the checkbox to an input field than why not just check the checkboxes by name. For example:
<input name="check1" value="checkbox 1 value" type="text"/>
<input name="check2" value="checkbox 2 value" type="text"/>
<input name="check3" value="checkbox 3 value" type="text"/>
then in php do:
$check1 = isset($_POST['check1']) ? $_POST['check1'] : "";
This way if the checkbutton is checked you get the value of check1 and otherwise it's empty.
Potentially, you are having issues because you can't have whitespace in the name attribute.
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
https://www.w3.org/TR/html401/types.html#type-name

Associative array from form inputs

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.

Can Grails handle POST variables as an array?

If you post the following HTML into a PHP script:
<input type="hidden" name="var[0]" value="A" />
<input type="hidden" name="var[2]" value="C" />
<input type="hidden" name="var[1]" value="B" />
You would end up with a variable called $_POST['var'] (that is essentially a HashMap) whose keys/values look like this:
[0] => "A"
[1] => "B"
[2] => "C"
In PHP, I'm then able to do basic array logic on this, for instance I can see that count($_POST['var']) == 3, and I can iterate over it with a foreach statement.
Is there any way to accomplish this, or something similar, in Grails? I noticed that if I pass in the same sort of HTML to Grails, the result is much less intuitive than it is in PHP. What I want to do is to simply be able to access params.var[0], params.var[1], and so on, and likewise be able to examine things like params.var.length.
But this is not the case. What happens is that params.var is undefined, but instead I then have to access request.getParameter('var[0]'), which is obviously pretty useless.
I realize that I could change my HTML to something like this:
<input type="hidden" name="var" value="A" />
<input type="hidden" name="var" value="B" />
<input type="hidden" name="var" value="C" />
But this is far from ideal, because then I have to guarantee that the HTML inputs are in precisely the right order every time. In PHP, it doesn't really matter what order they appear in since I can specify that directly in the name attribute, and the language is smart enough to take care of it.
Am I missing something? Is there any way to accomplish this in Grails?
Actually it does by default, when binding data. See http://grails.org/doc/latest/guide/theWebLayer.html#dataBinding Binding To Collections And Maps.
The data binder can populate and update Collections and Maps. The following code shows a simple example of populating a List of objects in a domain class:
class Band {
String name
static hasMany = [albums: Album]
List albums
}
class Album { String title Integer numberOfTracks }
def bindingMap = [name: 'Genesis',
'albums[0]': [title: 'Foxtrot', numberOfTracks: 6],
'albums[1]': [title: 'Nursery Cryme', numberOfTracks: 7]]
def band = new Band(bindingMap)
assert band.name == 'Genesis'
assert band.albums.size() == 2
assert band.albums[0].title == 'Foxtrot'
assert band.albums[0].numberOfTracks == 6
// ...
Also if you want to deal with this on your own, you can of course write it yourself. E.g.:
params.collect{it=~/${name}\[(\d+)\]/}.findAll().collectEntries{[it.group(1).toInteger(), params[it.group(0)]]}

Return value from element while showing another

Hi lets say I'm showing a numeric value in an element (not sure what element to use), what i want to achieve is once the numeric value is clicked (Thinking of onclick="this.form.submit();" or submit button) it will submit different designated value from the numeric value let us say. Apple then my sql query would retrieve apple and use it. NOTE: I have multiple numeric values and multiple designated values for each numeric value as an example it looks like this:
(numeric value) = (designated value)
15123 = apple
24151 = orange
39134 = peach
Here so far is what i have.
<input type='submit' name='searchthem' placeholder='<?php echo $numeric_value; ?>'
value='apple'>
** NOTE i have multiple numeric values with different designated value
And this is the SQL in the same page:
SELECT * from tbl_fruits where fruit_name='".$_POST['searchthem']."' ;
Would appreciate some help and ideas, If there is confusion please comment so i may further clarify.
Use select element and just submit the form so that it can process the values. if you wish to use AJAX, use some javascript and output the result in the browser.
If I understand your problem correctly you should add an array for the definition terms and do it like this:
<input type="hidden" name="searchterm" value="<?php echo $numeric_value; ?>" />
<input type='submit' name='send' value="<?php echo $names[$numeric_value]; ?>" />
Then in PHP switch through the values:
switch($_POST['searchterm']){
case(15123) $term = 'apple';break;
case(24151) $term = 'ornage';break;
case(39134) $term = 'peach';break;
}
This will secure your SQL query, too. [Beware: Never use unfiltered input (i.e. $_POST in your example) from the browser in SQL queries!]

Reading attribute values from HTML

I have HTML stored in a string. The markup contains form input fields called initval and endval which are the value attribute values I need. How can I get them from this string markup?
<form id="compute">
<input type="hidden" name="initval" value="tal:00far" />
<input type="hidden" name="endval" value="utl:80er" />
</form>
Presuming that the structure is very reliably like that, try the following:
$htmlCode = "...";
$matches = array();
if (preg_match_all('/name="(initval|endval)"\s+value="([^"]+)"/', $htmlCode, $matches)) {
$formValues = array_combine($matches[1], $matches[2]);
} else {
// error
}
This assumes only whitespace between the name and value attributes, you'll need to make a small change if it differs. preg_match_all() returns an array with the whole regexp match at [0], and then the individual group matches in their corresponding locations [1] & [2], the array combine takes one as keys, one as values and puts it together so you have an associative lookup to get your results.
If I have got your question right,
In HTML
<form id="compute" action="somefile.php" method="GET">
<input type="hidden" name="initval" value="tal:00far" />
<input type="hidden" name="endval" value="utl:80er" />
<input type="submit" value="Click!">
</form>
Upon clicking submit the data is sent the the php script, where it can be read as
$initval = $_GET['initval'];
$endval =$_GET['endval'];
EDIT: It seems I have got the question wrong, Sorry. :-(
Try Using htmldomlibraries for parsing html.

Categories