How can an id of input field can be read by PHP?
Solution 1
It depends which method you use for transferring the data (specified by the method
attribute of the form
element).
E.g. with:
<form method="POST">
<input type='text' id='float' name='attributename' value='' maxlength='30'/>
<input type="submit" />
</form>
you can access the data in PHP via $_POST['attributename']
when the form is submitted. $_POST
is an associative array that holds the data send via a POST request.
Note: The name
of the input element is the important property, not the ID. The ID is not transferred to the server, it plays only a role in the DOM. Only the name
and the value
is send to the server. So if you probably want to set name="float"
.
Further information: Variables From External Sources. You also might want to read about $_POST
and $_GET
(GET is the other method. This is used to send data via the URL).
Solution 2
You can't. When POSTing data to the server, the name
attribute is used. The id
has nothing much to do with PHP.
Solution 3
When PHP gets the data by GET or POST, it doesn't know the id of the input that was associated with a given piece of data. You do, however, know the name.
The simplest approach is to make the name and id match, or be able to derive the id from the name, like so:
name: float
id: float_id
name: address
id: address_id
The reason is that the DOM uses the id, but it has nothing to do with PHP's execution. PHP only gets the name. Since you have control of both server-side and client-side code, you can determine what the id will be by choosing a naming convention as I suggested above.
Solution 4
When you submit the form you would use the input name=""
attribute to pull the value from:
$_POST['attributename'];
Solution 5
First of all, an id
should be unique for each element.
You can suffix field name with []
to create an array so that you can process them later like:
<input type='text' id='float1' name='attributename[]' value='' maxlength='30'/>
<input type='text' id='float2' name='attributename[]' value='' maxlength='30'/>
<input type='text' id='float3' name='attributename[]' value='' maxlength='30'/>
Now from PHP, you can use foreach
to access each field value like this:
foreach($_POST['attributename'] as $value){
echo $value . '<br>';
}
If it is a single field though, you can access it just by its name:
echo $_POST['attributename'];
OM The Eternity
M a PHP Programmer.. And an Experienced Tester, And a Vocalist...
Updated on November 09, 2020Comments
-
OM The Eternity over 3 years
I have an HTML input field, and I have every input field specified with some id, now how can I use this input field id to identify the field.
Example:
<input type='text' id='float' name='attributename' value='' maxlength='30'/>
I need to verify the id of input field for float and then insert the input field's value in to db in particular field.
Please help me out..