$_POST unknown amount of elements - php

My idea is like an basket on a webshop.
I have a list of items filled into a form by php like:
<?php while($info=msqli_fetch_array($query)){ ?>
<Input type="text" id="someid1" value="<?php echo $info['info']; ?>">
<Input type="Checkbox" id="checkid1" value="1">
<Input type="Checkbox" id="checkid2" value="2">
<?php } ?>
I want to use POST for submitting.
on the next page for each line should be done this:
MYSQLI query
INSERT into booking (text,variable1,variable2)
VALUES ('$_POST['someid1']','$_POST['checkid1']','$_POST['checkid2']';
Is there a solution for this?

You can setup named inputs with brackets to get the results as an array server-side. For example:
<input type="text" name="fruits[1]" value="apple" />
<input type="text" name="fruits[2]" value="orange" />
on server side:
<?php
print_r($_POST['fruits']);
?>
array(
1 => 'apple',
2 => 'orange',
)
That solves the question. But your code suggests something else that should really be addressed.
You're asking for SQL injection if you just dump $_POST variables into a query. Use PHP's PDO functionality and parameterize your input. Look at the 2nd example in the answer at PHP PDO prepared statements for more info.

You could use a foreach but IMHO isn't a very secure thing what you want to do.

You should use arrays in your html, then you get the corresponding arrays in your $_POST array. Note that you need the name attribute:
<input name="someid[<?php echo $info['id']; ?>]" id="someid1" value="<?php echo $info['info']; ?>">
<input name="checkid[<?php echo $info['id']; ?>]" id="checkid1" value="1">
// etc.
Now $_POST['someid'], etc. will be arrays you can loop over.
Note that you need to use prepared statements to store the information in your database.

Related

How handle multiple inputs from one form in PHP

I'm not sure how to ask this question. It procedural question I believe.
<input type="hidden" name="1[]" value="dummy">
<input type="radio" name="1[]" value="5">
<label> Very Good </label>
<input type="radio" name="1[]" value="4">
<label> Good </label>
<input type="text" name="1[]" size="20">
<br>
<input type="hidden" name="2[]" value="dummy">
<input type="radio" name="2[]" value="5">
<label> Very Good </label>
<input type="radio" name="2[]" value="4">
<label> Good </label>
<input type="text" name="2[]" size="20">
$_POST output:
[1] => Array
(
[0] => Text misc
)
[2] => Array
(
[0] => 5
[1] =>
)
From this I construct and INSERT statement.
INSERT INTO coached_tracked (coached_id, value, note)
VALUES ($key, $value[0], $value[1]);
This is are dynamically generated form inputs. A radio button, text field pair.
How can I handle an occurrence where the radio is not selected and the text field has value, like in the first instance. I want the option of having nothing selected so a default value seems not called for. I tried with both with and without a dummy value (I saw an example suggesting a hidden field as a possible solution.)
Suggestions.
You should not tell the database what ID to use. Let the database itself determine that by using an auto-incremented column.
First, start with a logical input name. Using just numbers is extremely confusing and looking at your code, I have absolutely no idea what you're doing. We also want everything to go into the same PHP $_POST variable to not have to iterate over all possible number cominations. That means we can just iterate over the one single array.
Let's say you're adding a coach to a database, so logically we would start with:
<input name="coach">
Now when we want to add multiple coaches instead of just one, we can use HTML array names, however I would recommend you hard-code them instead of auto-incrementing in your HTML, which should simplify things later on. We also pluralize it to coaches:
<?php
for ($i=0;$i<10;$i++) {
?>
<input name="coaches[<?=$i?>]">
<?php
}
Now if each coach contains a certain properties, let's say name, salary, note, etc, we can add the properties to the input names like so:
<?php
for ($i=0;$i<10;$i++) {
?>
<input name="coaches[<?=$i?>][name]">
<input name="coaches[<?=$i?>][salary]">
<input name="coaches[<?=$i?>][note]">
<?php
}
Then in PHP you just iterate over $_POST['coaches'] and then use the properties for each coach how you wish:
if (isset($_POST['coaches'])) {
foreach ($_POST['coaches'] as $coach) {
$name = $coach['name'];
$salary = $coach['salary'];
$note = $coach['note'];
// Now execute the query:
// INSERT INTO coached_tracked (name, salary, note)
// VALUES ($name, $salary, $note);
}
}
Note: remember to sanitize any user-supplied data by using prepared statements with bound parameters to make sure you're not open to SQL injection attacks.

Assigning a text value to a PHP variable?

<input type="radio" name="package" value="SOME_VALUE_HERE">
I am using Joomla but i think its something related to PHP. I have a form on my website, and it has RADIO button , what i want is when the user submits the form with that RADIO BUTTON selected, in place of the value (SOME_VALUE_HERE) , i want something else to get stored in the database. That something should a 10-15 liner text. Can i make a $PHP variable and assign that 10-15 liner text to that variable and use it in place of the value=(SOME_VALUE_HERE).
Example :
<input type="radio" value="$phpvariable">
Where $phpvariable is a 10-15 liner text!
Hope you got my point!
You need to use php-tags and echo the php variable in the value of the input:
Assign value to php variable:
<?php $phpvariable = 'SOME LONG TEXT HERE'; ?>
The input:
<input type="radio" name="package" value="<?php echo $phpvariable; ?>">
You will also need a name for your input so that you can get the value
My suggestion would be to try:
<input type="radio" name="package" value="<?php echo htmlspecialchars($name); ?>">
If that does not work, just create a hidden field:
<input type="hidden" name="packageHidden" value="<?php echo htmlspecialchars($name); ?>">
function htmlspecialchars prevents XSS attacks as well.

MSSQL: multiple INSERTs with PHP arrays and echoing back the data

I have a form with the following structure:
<input type="text" name="projNo[1]" id="projNo[1]" value="<?php echo $row['ProjNo'
[1];>"
/>
<input type="text" name="projBudget[1]" id="projBudget[1]" value="<?php echo
$row['ProjBudget'][1]; ?>" />
<input type="text" name="projDateFrom[1]" id="projDateFrom[1]" value="<?php echo
$row['ProjDateFrom'][1]; ?>" />
<input type="text" name="projDateTo[1]" id="projDateTo[1]" value="<?php echo
$row['ProjDateTo'][1]; ?>" />
<input type="text" name="projNo[2]" id="projNo[2]" value="<?php echo $row['ProjNo'
[2];>"
/>
<input type="text" name="projBudget[2]" id="projBudget[2]" value="<?php echo
$row['ProjBudget'][2]; ?>" />
<input type="text" name="projDateFrom[2]" id="projDateFrom[2]" value="<?php echo
$row['ProjDateFrom'][2]; ?>" />
<input type="text" name="projDateTo[2]" id="projDateTo[2]" value="<?php echo
$row['ProjDateTo'][2]; ?>" />
There are two more groups like this with indexes 3 and 4. Upon submit, four separate records must be created in the DB if the user has filled in all four lines. My question is twofold: How would I structure my query to accomplish this? And: Have I set up my code correctly? When the form is loaded, I would like the correct output to be displayed. I've never been confronted with a request like this before, so I'm flying a bit blind.
Use PDO and prepared statements. Prepare a statement like this:
$s = $db->prepare('INSERT INTO PROJECT (no, budget, from, to) VALUES (?,?,?,?)')
Execute the statement for each set like this:
for ($i = 1; $i<=4; $i++) {
$s->execute(array($projNo[$i], $projBudget[$i], $projDateFrom[$i], $projDateTo[$i]));
}
(You need to add error checking and validation. This includes something that loads the stuff from $_POST to the arrays I used in the above example.)
Currently, you have a XSS security issue in your code. You cannot just echo stuff that comes from the user - you need to escape it. If you are putting it inside HTML, including double-quoted attribute values like in your case, use echo htmlspecialchars($_GET[...]);.
You may want to create a "htmlout" function that does nothing else than echo htmlspecialchars, just to have a nicer, easier-to-write name for it, and use it everywhere. That way, you can search your code for instances of "echo", and unless you have protected them otherwise, this indicates you probably need to add some escaping.

Iterating through set $_POST variables by type?

I have user inputs as follows:
<form action="special.php" method="post">
<input name="first1"> <input name="last1"> <input name="age1">
<input name="first2"> <input name="last2"> <input name="age2">
<input name="first3"> <input name="last3"> <input name="age3">
<input name="first4"> <input name="last4"> <input name="age4">
<input name="first5"> <input name="last5"> <input name="age5">
<input name="first6"> <input name="last6"> <input name="age6">
...
N
</form>
The amount of user inputs in the form is determined by the user; meaning, the user can add 5,10,20 additional lines to the code above, creating new input elements (following the pattern above) as they fit.
My question is, once the form gets submitted, what is an easy way to iterate and print out all the SET POST variables?
Something like:
for($i=0; $i < $numPostVars; $i++){
if(isset($_POST['first".$i."'])){
//echo all first names post variables that are set
}
}
// do the same from last names & age in separate loops
I think the trick is to name your variables slightly different, and take advantage of PHP's feature which will unpack them as arrays for you. Just use the syntax: first[1]. Then in PHP, $_POST['first']['1'] is where you will find it. You can then iterate all your "first" inputs with
foreach($_POST['first'] as $first_input) {
// ...
}
Also keep in mind that browsers may not send the field if it is empty when the user submits.
Here is what the inputs should look like in HTML:
<input name="first[1]"> <input name="last[1]"> <input name="age[1]">
As noted by user #DaveRandom, consider also a more hierarchical structure (think "rows" like from your db):
<input name="people[1][first]"> <input name="people[1][last]"> <input name="people[1][age]">
Inputs can be treated as arrays with a syntax very similar to that used in PHP:
<input name="name[1]" value="value 1">
<input name="name[2]" value="value 2">
This would result in a $_POST['name'] that looks like this:
array(
1 => "value 1",
2 => "value 2"
);
This principle can be expanded to incorporate multi-dimensional and associative arrays. So if you were to name your inputs like this:
<input name="rows[1][first]"> <input name="rows[1][last]"> <input name="rows[1][age]">
<input name="rows[2][first]"> <input name="rows[2][last]"> <input name="rows[2][age]">
...you would be able to easily iterate over $_POST['rows'] with a foreach construct. The data structure will be very similar to a set of database results.
foreach ($_POST['rows'] as $row) {
// do stuff with $row['first'], $row['last'] and $row['age'] here
}
A couple of things to note:
Unlike PHP, associative array keys in HTML do not require quotes, and using them will produce a result you may not expect. It will work, but not in the way you might think. You still need to use quotes in PHP though.
As far as I am aware, this syntax is not a W3C standard. PHP, however, always handles it as expected.

In a bit of a while loop mess!

I have spent quite some time making a function and the last 15-20 minutes trying to figure this out. I need help!
I am selecting multiple rows from the database and then running them in a while loop.
They are available on a dropdown menu.
<form method="POST" action="adminprocess.php">
<fieldset>
<p>
<label class="left2">League:</label>
<select name="league" class="combo">
<?php
$q = $database->selectAllLeagues();
while($row=mysql_fetch_assoc($q))
{
$theid = $row['id'];
extract($row);
?>
<option value="<? echo $theid; ?>">
<? echo $format.'_'.$game.'_'.$name.'_Season '.$season;?>
</option>
<?
}
?>
</select>
</p>
<p>
<input type="hidden" name="replaceleague" />
<input type="hidden" name="format" value="<? echo $format; ?>" />
<input type="hidden" name="game" value="<? echo $game; ?>" />
<input type="hidden" name="name" value="<? echo $name; ?>" />
<input type="hidden" name="season" value="<? echo $season; ?>" />
<input type='submit' class="button" value='Select league' />
</p>
</fieldset>
</form>
$theid seems to be working fine dependning on which row i select on the dropdown menu.
However, I cant get the values below in the hidden inputs to pass through the correct values from the row selected in the dropdown box.
It seems to always pass through the 4 variables from the first row of the database.
So basically, I need it to select the right row and use that data.
What am i doing wrong!!!
Thanks for reading!
Your hidden fields are initialized outside the loop, so they'll use the values that were left over from the last iteration of the while loop. (i.e. the last fetched row)
Why do you actually need the hidden fields in the first place? When you submit the form, the league field will contain the ID of the row selected in the drop-down box. Using the ID, you can fetch the other fields from the database when processing the form.
To directly answer your question about the while loop, it's because the hidden inputs are echoed outside the loop, after which data the last-iterated row from your database is used by PHP to output to those hidden inputs.
But I suggest that instead of using hidden form elements like that, you submit your form with the <option> with the value a user chooses, read the value (as in $_POST['league']), and fetch the row from your database with that ID and use it accordingly. (You may wish to keep the replaceleague hidden input if your application needs it of course.)
It's much easier, plus it ensures the information about the row a user chooses is coming from your database and not tampered with. In fact, for most applications this is the right way to go.

Categories