inserting array $_POST values to database using php - php

I have code which takes multiple values on post like`
<form id='students' method='post' class="form-horizontal no-margin" name='students' action='manage_shows.php'>
<input class="input-small" type="text" id='tamil' name='tamil[]' >
<input class="input-small" type="text" id='english' name='english[]' >
and so on..
When I try to insert db shows array values
include('config.php'); if(isset($_POST['submit'])) {
$tamil=$_POST['tamil'];
$english=$_POST['english'];
$sql = "INSERT INTO `shows` ( from , to , seats , cost , screen ) VALUES ('$fname','$lname','$tamil','$english','$computer')";
It inserts only array array into the database. How to add post values to the database ?
Thanks in advance
ameeth

You're using the [] notation on the field names. That tells PHP to treat those fields as multi-valued, and it will create a sub-array for each of them in $_POST. You will have to loop over those arrays and insert each value individually.
Also note that your code is vulnerable to SQL injection attacks.

you can use a foreach loop through the information collected as follows;
foreach ($_POST as $key => $value)
{
echo "$key = $value";
}

#Marc B's answer is correct, bu I'll take the liberty of adding a bit of detail. See, as already stated, the brackets you added to your inputs' names basically indicate that those inputs hold one of multiple values, i.e., that input is inside an array, so PHP is actually expecting an array of values for said post argument, like in this case:
<input class="input-small" type="text" id='tamil_1' name='tamil[]' />
<input class="input-small" type="text" id='tamil_2' name='tamil[]' />
<input class="input-small" type="text" id='tamil_2' name='tamil[]' />
When you send this, values will be parsed and placed in $_POST['tamil'], which will be an array with 3 values, the same happens to you, but you're sending only one value (as you understand, an array with one value, is still an array), so you have a structure that looks like this:
$_POST=array(
'tamil'=>array(...),
'english'=>array(...)
);
As stated by #Marc B, you can iterate through that array like so:
foreach($_POST['tamil'] as $k=>$v) {
//Do something with the value stored in $v or the key in $k
}
Now, you stated in a comment that you're new to PHP, so I'll clarify a bit regarding that behavior in which you insert rows with (array, array), when you try to place a variable inside a string, via concatenation or interpretation, like in your example (variables inside double quotes are interpreted by PHP before adding them to the string, as I suppose you're well aware since you used this syntax), said variables are first parsed into strings. Now, PHP is not the kind of fellow who questions what you're doing, so he will go with the flow most of the time and, instead of throwing an exception, he'll just cast your variable (whatever the type) into a string, how does he cast arrays into strings? by just returning 'array', of course.
So, in your code, PHP casts the arrays as strings and you end up having 'insert into table(col1,col2) values('.'array'.','.'array'.')'.

Related

How to fetch the only $_POST value

I'm trying to assign to a variable the unique index that is in $_POST.
I'm trying to do this, because the $_POST value will change for each button I press, and doing them all is like too long, plus, it's like a filer, every time you add a file, 3 new buttons appear, so too long.
The value either starts with 'edit', 'download', or 'delete', followed by the id of the selected file. For example, the 8th file will be deleted with 'delete8'.
I used filter to fetch the file id in my php file, but I can do it, only when I know exactly how the value is named.
Is there a way to select automatically the one and only value available in $_POST ?
array_keys will give you an array of keys in an array.
$name = array_keys($_POST)[0];
you can use,
foreach($_POST as $key => $value){
$posteddata[$key]=$value;
}
for fetching posted data
<input type="text" name="n1">
<input type="text" name="n2">
echo $posteddata['n1'];
echo $posteddata['n2'];

php and mysql variables

i have a web called Infomundo and under the site i have a problem with php:
$c=1;
while($c!=17)
{ $fecha_semana$c=$_POST['fecha_semana$c'];
$interes_semana$c=$_POST['interes_semana$c'];
$capital_semana$c=$_POST['capital_semana$c'];
$recargos_semana$c=$_POST['recargos_semana$c'];
$iva_semana$c=$_POST['iva_semana$c'];
$pagado_semana$c=$_POST['pagado_semana$c'];
$c=$c+1;
}
but the variables $fecha_semana$c, $interes_semana$c, etc. are wrong how can i fix it?
You're using single quotes in the array dereference:
$_POST['fecha_semana$c'];
That will not evaluate the value of $c; use double quotes:
$_POST["fecha_semana$c"];
See also: string
Additionally, you need to use variable variables for the left hand of the assignment:
${"fecha_semana$c"} = $_POST["fecha_semana$c"];
Update
This problem would be easier if you'd use array syntax in your form fields:
<input name="fecha_semana[]" value="123" />
<input name="fecha_semana[]" value="456" />
<input name="fecha_semana[]" value="678" />
When that gets posted, you will have an array in PHP:
print_r($_POST['fecha_semana']);
// ["123", "456", "678"]
As an alternative option to Jack's solution, you can use concatention:
$_POST['fecha_semana'.$c];
I personally prefer concatenation as it is easier for me to see where variables are being used, but I would say it is largely a matter of preference.

posting 2 values to array from single checkbox

I have a situation where I'd like to post two values to a search query string array from a single checkbox. Because of the design, I can't just add another checkbox.
The checkbox in question looks like so:
<input name="wpp_search[property_type][]" value="rental_home" type="checkbox" id="choice_c"/>
<label for="choice_c">For Rent</label>
what I now get in the query string is ...
{url}?wpp_search[property_type][0]=rental_home
but what I need is to tie two values to that one check so I end up with this:
{url}?wpp_search[property_type][0]=rental_home&wpp_search[property_type][1]=building
Any simple solutions? There is only one other checkbox that already feeds that array, so I could force this one to be
{url}?wpp_search[property_type][0]=rental_home&wpp_search[property_type][2]=building
You can seperate values with for example "|" like this value="value1|value2". Then later you can use the function explode: $p = explode("|", $value); and you get 2 values.
Generally it's not possible to send one value as two values.
One way I could imagine is that you reconfigure the ini-setting of arg_separator.input:
arg_separator.input = ";&"
This will allow you to use ; as well to separate values which then would allow you to inject the second value per that value:
<input name="wpp_search[property_type][0]"
value="rental_home;wpp_search[property_type][1]=building"
...
/>
If you make use of the value ; in other form values you naturally need to properly escape them to make this compatible.
Another way is that you insert a hidden field with that value and if your checkbox is checked, you change the name of it to the right name. If unchecked, you change the name of it back to something not right:
<input type="hidden" name="---wpp_search[property_type][1]" value="=building" />
Take the javascript reference of your choice and do the needed DOM manipulation on click of the other checkbox to remove the three --- at the beginning of the name.

Use $_POST values by number

i'm not sure how to explain it correctly, but i would like to use $_POST values like this $_POST[0] and not like this $_POST['form_field_name'].
Let's say i have 3 form fields so if i'd like to get data from post like this:
echo $_POST[0];
echo $_POST[1];
echo $_POST[2];
I hope you guys understand what i wanna do here.
Try it like this:
$values = array_values($_POST);
No idea why you would do such a thing though.
I would not recommend ever to refer to your $_POST values with indexes, as it is generally a bad idea.
You can access them by indexes if you do this:
$items = array_values($_POST);
$foo = $items[0];
$bar = $items[1]
You can also run through your values with a foreach loop, like this (which is better, but still bad!)
foreach($_POST as $item)
{
// do your thing here
}
$_POSTs variables depends on the name attribute of the form element as you can read in this link.
On the other hand the attribute name of the form elements according to W3C always must begin with a letter.
But I think you can prepare the $_POST variable before all your code (at the begining of your php script) with:
$arrPostVariables = array_values($_POST);
And then call them in the way as you want, but I think you will previously must detect the order of the array in order to avoid errors by not having the text of each variable.
This should work:
<input name="0" value="val0" />
<input name="1" value="val1" />

How to structure HTML form elements so they can be easily translated into a PHP object?

I am trying to figure out the best way to name my HTML form fields so that they can be easily parsed into a set of PHP opbjects.
For example I have the following table of elements: (let's assume it is inside a form)
<table>
<tr id='payment0'>
<td><input type='text' name='paymentType0'></td>
<td><input type='text' name='paymentAmount0'></td>
<td><input type='text' name='paymentAccount0'></td>
</tr>
<tr id='payment1'>
<td><input type='text' name='paymentType1'></td>
<td><input type='text' name='paymentAmount1'></td>
<td><input type='text' name='paymentAccount1'></td>
</tr>
</table>
Obviously I can write a bunch of code to search through the $_POST array to find all the paymentType/Amount/Account etc. values and put them into objects. However this feels a bit smelly and I am wondering if there is a better way to name these form elements?
On a side note, I had attempted to name the fields as control arrays (at least that's what I call them) so instead of paymentType0 it would be paymentType[0] and PHP would see them as an array that I could iterate though. The problem with this approach is that referencing these fields with jQuery becomes very difficult due to the square brackets.
What's the 'best of both' worlds solution for this?
You can use array without any problems, but don't call the fields paymentType[0], paymentAmount[0], ...
Instead, call them payment[0][type], payment[0][amount], etc.
Then the records will be conveniently grouped into associative arrays, which are much easier to manipulate:
foreach ($_POST["payment"] as $payment) {
echo "The type was $payment[type] and the amount was $payment[amount]";
}
As for the jQuery: follow David's suggestion. Objects in JavaScript are really just associative arrays with syntactic sugar and you can access their members as follows:
myForm["payment[0][amount]"].value = 300
You could consider preprocessing the submitted values with jQuery. Instead of submitting the raw form data you could structure them on the client-side and pass them to the server using JSON, which can easily be transformed into a PHP object.
Use the names with square brackets so that PHP's form processing library will convert them to arrays.
Then, if you need to reference them using JavaScript - use square bracket notation.
I agree with n3rd, if you're having trouble with the variables once passed through, pre-format your data on your end.
A litte extrapolation on this idea just means to store your data in a JSON object which you construct as the user enters values and then on submit send the JSON object to the next page instead of worrying about what each variable name is.
If that's not it, there is another possible solution although I'm not sure if it addresses your particular problem:
http://www.configure-all.com/arrayoffields.php
(grabbed from a google search on "php form names jquery array")
You can always try following code:
foreach($_POST as $key => $val)
{
if(isset($$key)) $$key = $val;
}
However this approarch is bad because you can POST variables like PHP_SELF etc, so you would like to check those.

Categories