I know there are similar topics out there but haven't been able to find what I'm looking for. So what I need to do is target a specific input name and foreach loop only that input instead of the whole form.
HTML look something like below.
<form action"<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" name="table1" method="post">
<input name="something1" type="text" />
<input name="something2" type="text" />
<input name="something3" type="text" />
<input name="something4" type="text" />
<input name="something4" type="text" />
<input name="something4" type="text" />
<input name="button" type="submit" value="Add" />
</form>
So I wanna loop every "something4" and just ignore the rest. Is this possible?
Just to explain what I want to do with the value is for every "something4" I'm gonna add a field to my DB and the input the respective input value into that field.
something like below...
$i = 0;
foreach ($_POST as $something4 => $something4_value) {
$add = mysqli_query($connect, "ALTER TABLE 'table' ADD something4$i VARCHAR( 255 ) NOT NULL") or die (mysql_error());
$sql_update = mysqli_query($con, "UPDATE 'table' SET something4$i='$something_value' WHERE id='$id'") or die (mysql_error());
$i++;
}
I hope this make sense! Thank you! :)
Create each of the name="something4" into an array like this:
<input name="something4[]" type="text" />
Then you can do a
foreach($_POST['something4'] as $something4) {
}
Related
I've been tearing my hair out trying to figure out why the isset($_POST['Submit']) is not executing with my form. The data from the form is just not passing into the php code. Basically the code does not seem to be recognizing something like $ffname = $_POST["ffname"];
<?php
$ffname = $flname = $femail = $fcemail = $fpass = $fcpass = "";
if(isset($_POST['ffname'])){
$ffname = $_POST["ffname"];
$flname = $_POST["flname"];
$femail = $_POST["femail"];
$fcemail = $_POST["fcemail"];
$fpass = $_POST["fpass"];
$fcpass = $_POST["fcpass"];
echo "<p>Hello World<p>";
$con = mysqli_connect("localhost", "root", "") or die(mysqli_error());
mysqli_select_db($con, "userdata") or die(mysqli_error($con));
mysqli_query($con,"INSERT INTO tbluser (fname, lname, email, pass) VALUES('$ffname', '$flname', '$femail', '$fpass')")
or die (mysqli_error($con));
}
?>
<form method="post">
First Name: <input type="text" name="ffname" id="ffname" value="<?php echo $ffname;?>"><br>
Last Name: <input type="text" name="flname" value="<?php echo $flname;?>"><br>
E-mail: <input type="email" name="femail" value="<?php echo $femail;?>"><br>
Confirm E-mail: <input type="email" name="fcemail" value="<?php echo $fcemail;?>"><br>
Password: <input type="password" name="fpass" value="<?php echo $fpass;?>"><br>
Confirm Password: <input type="password" name="fcpass" value="<?php echo $fcpass;?>"><br>
<input type="submit" name="Submit" value="submit">
</form>
The other answer by #DerVO is correct. But there seems to be something else at play, since you say it still doesn't work.
A comment became too long, so I've built a full answer here.
Step 1:
Add a name to your input:
<input type="submit" name="Submit" value="submit">
However, relying on the submit in your $_POST is not the best plan. So I suggest watching a different form field - for example, ffname:
Step 2:
Improve your watch, using a different field:
if ( isset( $_POST['ffname'] ) ) {
// do your work
}
Lastly, you may be munging your form action attribute.
Step 3:
In order to keep things simple, if the form is supposed to submit to the same page, you can simply omit the form action.
<form method="post">
Betweeen these three items, the form will work, unless you have some problem with your server.
Step 4:
Clean up your form formatting. You've got odd spacing which is problematic. In an html element, the property="value" code needs to be without spaces, but spaces between properties. Example:
<!-- Your version -->
<input type = "text"name = "ffname"id = "ffname"value="<?php echo $ffname;?>"><br>
<!-- Clean / correct version -->
<input type="text" name="ffname" id="ffname" value="<?php echo $ffname;?>"><br>
Here's a "clean" version of your whole form:
<form method="post">
First Name: <input type="text" name="ffname" id="ffname" value="<?php echo $ffname;?>"><br>
Last Name: <input type="text" name="flname" value="<?php echo $flname;?>"><br>
E-mail: <input type="email" name="femail" value="<?php echo $femail;?>"><br>
Confirm E-mail: <input type="email" name="fcemail" value="<?php echo $fcemail;?>"><br>
Password: <input type="password" name="fpass" value="<?php echo $fpass;?>"><br>
Confirm Password: <input type="password" name="fcpass" value="<?php echo $fcpass;?>"><br>
<input type="submit" name="Submit" value="submit">
</form>
You need to give your input submit a name:
<input type="submit" name="Submit" value="Submit">
You have pass name of element in $_POST
try put name attribute in input submit
<input type = "submit" name="Submit" value = "1">
Hi I'm quite new to php and I'm currently making a webpage similar to the ones used by supermarkets for stock management control as part of an assignment. I have the following form where the cashier would enter the product Id and the quantity of the item being purchased.
The form will then call another php file named cashsale.php which will take these inputs and update the tables in my database so that levels of stock on shelves in supermarkets are up to date with the new amounts (i.e. older qty - qty entered) and management can be advised when reorder is needed.
As it is the form works well, however I was advised to edit it in a way that a cashier can enter multiple products and quantities before submitting (i.e. the form will sort of show itself again) and allow the user to edit or remove any items before actually submitting the values to cashsale.php to manipulate the tables. I seem to be at a loss as to how this can be done.
I wanted to create a new button named "Add" which would display the form again, i.e. allow the user to check in more items, but I am confused as to how this can be done and also as to how I will be able to update tables then since I would be having more then just 2 inputs.
Can anyone help me on this please? Thanks in advance. The following is my html form:
center form action="cashsale.php" method ="post"
Product ID: <input name= "id" type="int" > <br>
Quantity:<input name="qty" type="int">
<input type="button" name = "Add" onclick="add">
<input type="Submit" name ="Submit" value = "Submit">
form center
I was not allowed to use html tags for form and center so I removed the < >. The following is some of the modifications done in the cashsale.php file just to give a clearer example.
$result = mysql_query("SELECT * FROM shelfingdetails where prodId =' " .$id. " '");
if (!$result){
die (mysql_error());
}
while ($row =mysql_fetch_array($result))
{
$qtyOnShelf= $row ['QtyOnShelf'];
$max=$row['max'];
$newQtyShelf=$qtyOnShelf-$qty;
}
$update=mysql_query("UPDATE shelfingdetails SET QtyOnShelf ='". $newQtyShelf. "' where prodId = '". $id. "';");
I hope someone can help. Thanks!
You just have to pass an array. For this you have to generate the inputs with PHP or javascript (I'm gona use jQuery to keep the code nice and simpe).
If you use PHP:
// PHP
<?php
if(isset($_POST['submit']) && $_POST['submit']){
//save data
} elseif(isset($_POST['Add']) && $_POST['Add']) {
$max = (int)$_POST['max']
} else { $max = 1; }
?>
<form action="" method="post">
<?php
for($i = 0;$i < $max;$i++){
?>
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int">
<?php
}
?>
<input type="hidden" name="max" value="<?= $i; ?>" />
<input type="submit" name="Add" />
<input type="submit" name="Submit" value="Submit" />
</form>
If yo use Javascript:
//HTML
<form action="" method="post" id="form">
<div id="add">
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int">
</div>
<input type="hidden" name="max" value="<?= $i; ?>" />
<input type="button" name="Add" onclick="addRow();" />
<input type="submit" name="Submit" value="Submit" />
</form>
// jQuery
function addRow(){
$("#add").append("<br />Product ID: <input name='id[]' type='int' >" +
"<br />Quantity: <input name='qty[]' type='int'>");
}
you have to use id[] and qty[] to pass them as an array and with the add button generate as many of them as you need. Like so:
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int"> <br>
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int"> <br>
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int">
<input type="button" name = "Add" onclick="add">
Then on the backand use for loop to save all the data.
$max = count($_POST['id']);
$id = $_POST['id'];
$newQtyShelf = $_POST['qty'];
for($i = 0;$i < $max;$i++){
$update=mysql_query("UPDATE shelfingdetails
SET QtyOnShelf ='". (int)$newQtyShelf[i]. "'
WHERE prodId = '". (int)$id[i]. "';");
}
I just wanted to show you the idea, please don't use this specific code, because you should use mysqli instead of mysql and also mysqli_escape_string to make sure that the user not submits incorrect data.
I have the following form:
<form action="options.php" method="post">
<input type="text" name="deptid" id="deptid" />
<input type="text" name="deptname" id="deptname" />
<input type="submit" name="submit" id="submit" value="save" />
</form>
EDIT
Is it possible to pass the two values into one associative array BEFORE submission ?
I would like to pass it in this form:
array('deptid'=>'deptname')
I need this because I avoid to modify the script of the destination php file(options.php)
Thanks.
Here is a method using pure HTML that get's you nearly exactly where you want to be, and only uses HTML:
<form action="options.php" method="post">
<input type="text" name="options[deptid]" id="deptid" />
<input type="text" name="options[deptname]" id="deptname" />
<input type="submit" name="submit" id="submit" value="save" />
</form>
Which would give you in PHP:
$post_options = array(
'options' => array(
'deptid '=> '[that input element value]',
'deptname' => '[that input element value]'
)
);
Which you can then (including sanitizing) access such as this:
$post_options = array('options');
if (is_numeric($post_options['deptid'] && $post_options['deptid'] > 0) {
// Do whatever
}
if (is_string($post_options['deptname'] && strlen($post_options['deptname'] > 2)) {
// Do whatever
}
EDIT
Or... You want to reference the deptid in the input name attribute and use it to modify the row for a department name? Which seems to indicate something like this:
<?php
$deptid = 1;
$deptname = 'Department of Silly Walks';
?><input type="hidden" name="options[<?=$deptid?>]" value="<?=$deptname?>">
Which outputs:
<input type="hidden" name="options[1]" value="Department of Silly Walks">
http://codepad.org/DtgoZGe7
The problem with this is that the $deptid value becomes a value that's not actually directly named or referenced. I think this is potentially problematic to implement due to this abstraction of the value from the server to the client and back, so I would recommend what I have at the top instead. It's not much of a difference in practice, but it's more or less self-documenting.
Note, if you wanted to serialize a list of departments, it's a little trickier. You might, for instance, try this:
<input type="text" name="options[][deptid]" id="deptid" />
<input type="text" name="options[][deptname]" id="deptname" />
Which would add an indexed value for every input. However... They were would not be directly associated. So you would get, instead, two zero-indexed arrays for each key.
What I would suggest in this case is to use Javascript to add each new department's input elements, so you can give each a number like:
<input type="text" name="options[0][deptid]" id="deptid" />
<input type="text" name="options[0][deptname]" id="deptname" />
<br/>
<input type="text" name="options[1][deptid]" id="deptid" />
<input type="text" name="options[1][deptname]" id="deptname" />
<br/>
<input type="text" name="options[2][deptid]" id="deptid" />
<input type="text" name="options[2][deptname]" id="deptname" />
<br/>
<input type="text" name="options[3][deptid]" id="deptid" />
<input type="text" name="options[3][deptname]" id="deptname" />
Or do the old-school POSTBACK method and use PHP to count $POST['options'] and "manually" add a new "row" of inputs with the same index. It's a common trap, so you just have to think about it if this is what you're after at some point.
$_POST is already an associative array and I recommend you not to complicate things beyond that because $_POST already holds the data came from your form.
$myassoc = $_POST;
print_r($myassoc);
and the associative array that you will receive is organized and named same in the name attribute of the input elements in your form (including textarea)
Other Insights
As I see your code you want to put the deptname data to deptid as it reaches the PHP server-side code. well the thing you can do with is is just assign it to the key deptid
$_POST['deptid'] = $_POST['deptname'];
$myassoc = $_POST;
print_r($myassoc);
<form method="post">
<input type="text" name="formdata['deptid']" />
<input type="text" name="formdata['deptname']" />
<input type="submit" />
</form>
<?php
if(isset($_POST['formdata']))
{
$deptid = $_POST['formdata']['deptid'];
$deptname = $_POST['formdata']['deptname'];
}
?>
Build a JS object with the appropriate structure, convert it to JSON with JSON.stringify(), POST it, and then do json_decode($_POST['data'],true).
You'll have an exact copy from JS object, to PHP associate array. Drop the second parameter of true to get a PHP object.
$_POST is already an associative array.
You can rebuild an array of the form you need from this by just assigning $_POST to a variable
$myarray = $_POST;
Now $myarray is what you require. Do var_dump($myvar);.
Why would you want to do that?
But, you CAN send "arrays" through forms like this:
<form method="post">
<input type="text" name="textboxes[]" />
<input type="text" name="textboxes[]" />
<input type="submit" />
</form>
<?php
if(isset($_POST['textboxes']))
var_dump($_POST['textboxes']);
?>
$deptid = $_POST['deptid'];
$array = array($$deptid => $_POST['deptname']);
print_r($array);
I have a form with a variable number of inputs. The inputs are inside the table and I need to get three values from them: the row, the column and the actual value inside the input.
Some may be populated some may not and I need all their values to update a mysql db (row and column to know what to update, value to know the new value to insert in the database).
This is my form (an example version of it):
<form method="post" action="">
<input name="data[111][222]" value="2" />
<input name="data[112][221]" value="0" />
<input name="data[113][223]" value="4" />
//goes on
<input name="data[324][435]" value="11" />
<input name="data[325][436]" value="" />
</form>
And that's as far as I go. How can I get the data from this form so I can do a simple update in my database that goes like this (for all the affected inputs):
update table set res="value_from_input" where row="row_value" and col="col_value"
<form method="post" action="">
<input name="data[111][222]" value="2" />
<input name="data[112][221]" value="0" />
<input name="data[113][223]" value="4" />
<input name="data[324][435]" value="11" />
<input name="data[325][436]" value="" />
<input type="submit" />
</form>
<?php
foreach ($_POST['data'] as $k1 => $v1)
{
foreach ($v1 as $k2 => $v2)
{
echo "<p>k1:".$k1."; k2: ".$k2."; value: ".$v2."</p>";
$query = "update table set res='$v2' where row='$k1' and col='$k2'";
mysql_query($query);
}
}
?>
foreach($_POST['data'] as $row => $row_array)
{
foreach($row_array as $col => $value)
{
// Sanitize all input data before entry
$mysql = "UPDATE table SET res='$value' WHERE row='$row' AND col='$col'";
}
}
I'm trying to upload a form to the database, that uses the same field names, as part of a CMS.
This is the form (I have used JQuery to multiply the div the number of options per product):
<form method="post" enctype="multipart/form-data" action="testing.php">
<div class="OptExtra1">
<h3>Additional Option</h3>
<label for="RESAddType">File type (i.e. “CD” or “Download”)</label>
<input name="RESAddType[]" type="text" id="RESAddType" size="48" class="FW" />
<label for="RESAddTitle">File title (i.e. “Boxed Set of 4 CDs”)</label>
<input name="RESAddTitle[]" type="text" id="RESAddTitle" size="48" class="FW" />
<label for="RESAddFType">File format (As “MP3” // “WORD” // “PDF”)</label>
<input name="RESAddFType[]" type="text" id="RESAddFType" size="48" class="FW" />
<label for="RESAddPrice">File price (Enter as “6.99” – <strong>NO “£” SIGN!</strong>)</label>
<input name="RESAddPrice[]" type="text" id="RESAddPrice" size="48" class="FW" />
<label for="RESAddFName">File name</label>
<input name="RESAddFName[]" type="text" id="RESAddFName" size="48" class="FW" />
<label for="RESAddTxt">File text</label>
<textarea name="RESAddTxt[]" id="RESAddTxt" cols="70" rows="50" class="mceAdvanced"></textarea>
<label for="RESAddSample">File text</label>
<textarea name="RESAddSample[]" id="RESAddSample" cols="70" rows="50" class="mceVSimple"></textarea>
<input type="button" value="Add another option" class="SubmitButton" onclick="inserter()" />
<hr />
</div>
<p><input type="submit" name="submit" value="Add Resource" class="SubmitButton"/><input type="hidden" name="RESCatCode" value="2" /><input type="hidden" name="RESCatSubCode" value="5" /><input type="hidden" name="submitted" value="true" /></p>
and this is what I have so far for the PHP
if(isset($_POST['submitted'])){
$RESCode = 100;
$RESAddType = $_POST['RESAddType'];
$RESAddTitle = htmlentities($_POST['RESAddTitle'], ENT_QUOTES);
$RESAddFType = $_POST['RESAddFType'];
$RESAddPrice = $_POST['RESAddPrice'];
$RESAddFName = $_POST['RESAddFName'];
$RESAddTxt = mysql_real_escape_string($_POST['RESAddTxt']);
$RESAddSample = mysql_real_escape_string($_POST['RESAddSample']);
for ($i=0; $i < count($_POST['RESAddType']); $i++) {
$OptionQuery = mysql_query ("INSERT INTO ResAdd (RESAddCode, RESCode, RESAddType, RESAddTitle, RESAddFType, RESAddPrice, RESAddFName, RESAddTxt, RESAddSample) VALUES ('', '".$RESCode."', '".$RESAddType."', '".$RESAddTitle."', '".$RESAddFType."', '".$RESAddPrice."', '".$RESAddFName."', '".$RESAddTxt."', '".$RESAddSample."');");
}
header("Location: welcome.php");
exit;
}
It kind of worked, but is just putting in the word "array" into the database. Also the htmlentities and mysql_real_escape_string posts don't upload anything to the database.
Any ideas please?
You've forgotten something :)
$OptionQuery = mysql_query ("INSERT INTO ResAdd (RESAddCode, RESCode, RESAddType, RESAddTitle, RESAddFType, RESAddPrice, RESAddFName, RESAddTxt, RESAddSample) VALUES ('', '".$RESCode[$i]."', '".$RESAddType[$i]."', '".$RESAddTitle[$i]."', '".$RESAddFType[$i]."', '".$RESAddPrice[$i]."', '".$RESAddFName[$i]."', '".$RESAddTxt[$i]."', '".$RESAddSample[$i]."');");
Look at all these $i in the code above. If you don't use them, the script will try to use the entire array (and trying to print or save an array as a string always results in printing "Array").
P.S.I've edited my answer. Sorry for the previous one, I've misunderstood the code and posted a wrong answer.
You need to looping
$cnt=count($_POST['RESAddType']);
for ($counter=0; $counter < $cnt; $counter++)
{
$_POST['RESAddType'][$counter]// to access the value
$_POST['RESAddPrice'][$counter]//
//create your query here
}