Upload multiple form $_post arrays to database - php

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
}

Related

Placing data in MySQL database from form fields created on the fly

I have a form that allows members to click a (+) sign, and it will put another form field there. They can do this to basically without limit.
The problem I have is if they do it, let's say, 3 times and fill out all 3, when I get the data to save it, it's placing the first field in the database and not the others.
Here is my code:
Here is the JavaScript that makes the div show as they push the (+) sign.
<script type="text/javascript">
function add_feed()
{
var div1 = document.createElement('div');
div1.innerHTML = document.getElementById('newlinktpl').innerHTML;
document.getElementById('newlink').appendChild(div1);
}
</script>
<style>
.feed {padding: 5px 0}
</style>
This is part of the form that does the above...
<td width="50%" valign="top">
<div id="newlink">
<div class="feed">
<input type="text" size="45" value="" name="recname[]" placeholder="Place Company Name Here"><br /><br />
<input type="text" size="45" value="" name="reclink[]" placeholder="Place URL Here"><br /><br />
<p><b>What Type Of Page Is This?</b><br /><br />
<input type="radio" name="rectype[]" value="1"> Business Opp<br />
<input type="radio" name="rectype[]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[]" value="3"> Tools Site<br /></p>
</div>
</div>
<hr>
<p id="addnew">
+ Click Here To Add Another Biz/Traffic/Tools Site
</p>
<div id="newlinktpl" style="display:none">
<hr>
<div class="feed">
<input type="text" size="45" value="" name="recname[]" placeholder="Place Company Name Here"><br /><br />
<input type="text" size="45" value="" name="reclink[]" placeholder="Place URL Here"><br /><br />
<p><b>What Type Of Page Is This?</b><br /><br />
<input type="radio" name="rectype[]" value="1"> Business Opp<br />
<input type="radio" name="rectype[]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[]" value="3"> Tools Site<br /></p>
</div>
</div>
This is the part of the PHP code that would save it...
$i=0;
$linkname = $_POST["recname"][0];
while($linkname != ""){
$linkname = $_POST["recname"][$i];
$linkurl = $_POST["reclink"][$i];
$linktype = $_POST["rectype"][$i];
$linkname = $res->real_escape_string($linkname);
$linkurl = $res->real_escape_string($linkurl);
$linktype = $res->real_escape_string($linktype);
$result299 = mysqli_query($res, "INSERT INTO user_links (linkname,linkurl,linktype,sort) VALUES ('$linkname','$linkurl','$linktype','0')");
$i++;
}
It's all working except that is does not store all the data in the database (only the first one saves). That's the part I need help with please.
Please explain what I have done wrong and how to get it to store all the fields in the database, no matter how many the user creates and fills out.
I tested your code and it works fine so far if I use it like this:
$i=0;
$linkname = $_POST[recname][0];
while($linkname != ""){
$linkname = $_POST[recname][$i];
$linkurl = $_POST[reclink][$i];
$linktype = $_POST[rectype][$i];
echo "INSERT INTO user_links (linkname,linkurl,linktype,sort) VALUES ('$linkname','$linkurl','$linktype','0')<br>\n";
$i++;
}
There's no information about the $res object you're calling real_escape_string() on, so I'll just skip that for now. There are a couple of weaknesses in the code though:
You are referencing the post keys with barenames instead of strings.
PHP will gracefully assume you meant it as a string, but it will trigger a notice like Use of undefined constant recname - assumed 'recname'. Enclose them in quotes to make it clean.
Your use of the loop will result in an empty element inserted in the database every time.
You set the new linkname AFTER checking if $linkname is empty, but the variable contains the name of the last iteration. Instead, do something like this:
$i=0;
while($linkname = $_POST["recname"][$i]){
$linkurl = $_POST["reclink"][$i];
$linktype = $_POST["rectype"][$i];
echo "INSERT INTO user_links (linkname,linkurl,linktype,sort) VALUES ('$linkname','$linkurl','$linktype','0')<br>\n";
$i++;
}
Your code only allows for one radio button to be checked at a time
You cannot use rectype[] as a name for radio buttons, as an equal name forms a group of radio buttons out of all the elements. You need to name them like this:
<input type="radio" name="rectype[0]" value="1"> Business Opp<br />
<input type="radio" name="rectype[0]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[0]" value="3"> Tools Site<br />
<input type="radio" name="rectype[1]" value="1"> Business Opp<br />
<input type="radio" name="rectype[1]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[1]" value="3"> Tools Site<br />
and so on. You can do that programatically in your javascript code like this:
<script type="text/javascript">
var counter = 1;
function add_feed()
{
var div1 = document.createElement('div');
div1.innerHTML = document.getElementById('newlinktpl').innerHTML;
var inputs = div1.getElementsByTagName('input');
for (i=0; i<inputs.length; i++) {
if (inputs[i].type == "radio") {
inputs[i].name="rectype[" + counter + "]";
}
}
counter++;
document.getElementById('newlink').appendChild(div1);
}
</script>
That said, I don't see why it should only save one item, unless you have a key constraint hitting or something else we cannot assume from the piece of code you shared.

PHP simple form not posting

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">

Foreach input php and mysql

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) {
}

Keep printing same form until submit button is clicked

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.

Checkbox Take Value From Textbox

I have a problem to combine the checkbox and textbox values. Here my snipet code :
<input type="checkbox" name="id_staf[]" value="query from database">
<input type="text" name="note[]" value="any text entered">
<br>
<input type="checkbox" name="id_staf[]" value="query from database">
<input type="text" name="note[]" value="any text entered">
<br>
<input type="checkbox" name="id_staf[]" value="query from database">
<input type="text" name="note[]" value="any text entered">
<br>
this is my php code to process that form:
$array_id_staf = $_POST['id_staf'];
$array_note= $_POST['note'];
for($a = 0; $a < count($array_id_staf); ++$a) {
echo $query1 = "UPDATE peserta SET note='$array_note[$a]' WHERE id= '$array_id_staf[$a]'<br>debugging";
//----------------------testing---------------------------#mysql_query($query1); // hold first for debugging
} // Closing for
if all checkbox were checked, the result os going fine. But if the second and 3rd were checked, array $array_note become wrong.
Please help me. Thanks in advance.

Categories