Jump to content

Help with Form Values


headmine

Recommended Posts

Ok so I have a form that will dynamically add fields to insert more info. Here is the code for that.

 

<form id="form1" name="form1" method="post" action="process.php">
  Company Name<br />
    <label>
  <input name="company" type="text" id="company" />
    </label><br />
Bullet Points<br />
<div id="myDiv"></div>
<label>
<input type="submit" name="Submit" value="Submit"/>
</label>
</form>
<input name="hidden" type="hidden" id="theValue" value="0" />
<p><a href="javascript:;" onclick="addElement();">Add bullet point</a></p>

 

The Process.php file looks like this.

 

foreach($_POST as $key => $value) 
if ($value == "Submit") {
} else {
if (strpos($key, "bp")) { 
$theString = "$value,";
}
echo "$key: $value<br>";
echo $theString;
}

 

What I am trying to do is exclude submit as a value.

The form key that is duplicated is bp followed by its number ex.

 

bp1 = a

bp2 = b

bp3 = c

etc

 

I would like the values of only those keys to create a string.

 

example

 

$theString = "a,b,c";

 

I thought the above code would work. but it doesnt.

 

What am I doing wrong?

 

Also the idea behind this is to allow submission of a "Company Name" Once they enter the company name they can add bullet points to the form for the company.

 

I figured the easiest way to do this is the above method since I never know how many bullet points will be needed.

 

So the SQL statment would be something like

 

"INSERT INTO company (uid, bulletPoints) VALUES('$uid', '$theString'"

 

Am I going about this in the wrong way?

 

Thanks in advanced for any help!

 

Link to comment
Share on other sites

I am assuming that the resultant string results in a string like 1,2,3... or a,b,c,... right?

 

If so, try this:

<?php
$iter=0;
foreach($_POST as $key => $value){
     if($iter>0)$theString .= ",";
     if ($value == "Submit") {
     } else {
          if (strpos($key, "bp")) {
          $theString .= $value;
          $iter++;
     }
     echo "$key: $value<br>";
}
echo $theString;
?>

Link to comment
Share on other sites

@radi8

Correct me if I'm wrong, but since 'bp' is at the zero position, don't you need to write:

<?php
if (strpos($key, "bp") !== false) {
}
?>

Because, while the zero position is not false, it is also, technically, not true? At least, that's what the manual seems to say:

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

 

@headmine

Question: wouldn't it be easier to let php create an array out of a series of form elements with [] at the end of their names (ie <input name="bp[]">)? Then you could implode() one element.

Link to comment
Share on other sites

@radi8

 

That didn't seem to do anything?

 

@mikr

 

What you did worked. But it duplicated 1 value this is how it printed out

 

a,b,c,d,d

 

d was not duplicated from the form so somewhere in the script it causes it to duplicate.

 

Here is what I am running.

 

foreach($_POST as $key => $value) 
if ($value == "Submit") {
} else {
if (strpos($key, "bp") !== false) {
$theString = "$value,";
}
#echo "$key: $value<br>";
echo $theString;
}

 

So it works! That's the first phase. But when inserting into the SQL database I need to remove that last "," how would I do that?

 

I tried

 

$newString = rtrim($theString, ",");
echo ($newString);

 

but that just removed ALL commas. Which I don't want.

Link to comment
Share on other sites

This is driving me insane. Why does it remove ALL the commas? I only want it to remove the last character

 

$string = substr($str, 0, -1);
echo ($string);

 

this echos a,b,c,

 

$string = substr($str, 0, -2);
echo ($string);

 

this echos

 

abc

 

How do I only remove the last character?

Link to comment
Share on other sites

When you want to create comma separated items, implode($glue,$pieces) is awesome. In your case, you want to put all of the post variables you want into your own array ($pieces) and then use as your glue ",". That way, you only get commas in between each item.

<?php
$array = array(); // our empty array
foreach($_POST as $key => $value) {
    if ($value == "Submit") {
    } elseif (strpos($key, "bp") !== false) {
        array_push($array,$value); // adding $value to the array $array
    }
}
$theString = implode(',',$array); // creating our string.
// if you want quotes around each, then you would have done...
// $theString = "'".implode("','",$array)."'"; // those are double quotes surrounding single quotes.
echo $theString;
?>

 

Also, the reason why it repeated the 'd' in your code is because you were printing each letter within the loop, but outside of the if/else statement. So, when you got to the submit button, while it didn't process the submit button like a bp element, it still executed the line that read: echo $theString. And $theString still had the value "d," in it.

Link to comment
Share on other sites

Also, just to make sure you know this (if you do, my apology). If you have form elements in a web page that have the same name with square brackets at the end (ie element[], element[], and element[]), then, when they get submitted to php, they will end up in $_POST['element'] as an array. So if you have three fields:

<input type="text" name="element[]" value="fred" />
<input type="text" name="element[]" value="frank" />
<input type="text" name="element[]" value="bertha" />

These three field will appear in $_POST as follows:

<?php
$_POST['element'][0] = 'fred';
$_POST['element'][1] = 'frank';
$_POST['element'][2] = 'bertha';
?>

Which is really cool, because then you can easily do an implode on those values alone:

<?php
$string = implode(',',$_POST['element']);
print $string; // will print fred,frank,bertha
?>

And I know you can do this with javascript, as I had to implement this type of feature in an application just last week. PHP will receive them in the order that they appear within the html document (so, if you give the user the tools, they can rearrange them, if you'd like).

Link to comment
Share on other sites

  • 2 weeks later...

Ok new problem...

 

The form Needs to collect Company Name, and Contact Number(s).

 

So Here is the form.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Insider Tips and Updates</title>
<script>
function addElement() {
  var ni = document.getElementById('myDiv');
  var numi = document.getElementById('theValue');
  var num = (document.getElementById('theValue').value -1)+ 2;
  numi.value = num;
  var newdiv = document.createElement('div');
  var divIdName = 'my'+num+'Div';
  newdiv.setAttribute('id',divIdName);
  newdiv.innerHTML = '<input name="aNumber[]" type="text" id="aNumber" size="12" /> <select name="aNumber[]"> <option value="Option">Option</option> <option value="Extension" selected="selected">Extension</option> </select> <input name="extOp[]" type="text" id="extOp" size="6" /><a href=\'#\' onclick=\'removeElement('+divIdName+')\'>Remove this number</a>';
  ni.appendChild(newdiv);
document.getElementByID('howMany').value = num;
}
function removeElement(divNum) {
  var d = document.getElementById('myDiv');
  var olddiv = document.getElementById(divNum);
  d.removeChild(olddiv);
}
</script>
</head>
<body>

<form id="form1" name="form1" method="post" action="process.php">
  Company Name<br />
    <label>
  <input name="company" type="text" id="company" />
    </label><br />
Contact Numbers <br />
<div id="myDiv"></div>
<label>
<input type="submit" name="Submit" value="Submit"/>
</label>
</form>
<input name="hidden" type="hidden" id="theValue" value="0" />
<p><a href="javascript:;" onclick="addElement();">Add contact number</a></p>
<p>

</p>
<p> </p>
</body>
</html>

 

If there is more than one contact number the user can click "ADD CONTACT NUMBER" and another dynamic field is added.

 

There is an input for: Phone Number, Option for Extension/Option, and the Extension/Option Number.

 

I added a drop down menu for the user to select weather they need an extension or option number.

its named select[]

 

So there are 3 different form variables being passed here.

 

aNumber[], select[], and extOp[]

 

So what I need the php script to do is create a string for each dynamic field that looks something like this

 

$contact = aNumber[] . select[] . extOp[];

 

if there are more than one contact number then i'd like them to be added to $contact but seperated by comma's because they will be inserted into a database.

 

So I tried

 

$i = 0;

foreach ($_POST["aNumber"] as $key)
$i++;
echo $i;

$j = 0;
while ($j<=$i) {
$content = $_POST["aNumber"] . "," . $_POST["select"] . "," . $_POST["extOp"]; 
$j++;
}
echo $content;

 

That didn't work.

 

So I am stuck...

 

Thanks in advance for any help

 

Link to comment
Share on other sites

First, a minor point on the html. You've named the input and the select both "aNumber[]", and as your comments indicate, select ought to be named "select[]".

 

Second, I thought I'd walk through your code and tell you what it tells me.

<?php
$i = 0;   // initialize $i
// for every element $key in the array $_POST["aNumber"], add 1 to $i
foreach ($_POST["aNumber"] as $key) 
$i++;
echo $i; // so $i = count($_POST["aNumber"])

$j = 0;
while ($j<=$i) {  // loop $i times.
// append the arrays $_POST["aNumber"], $_POST["select"], and $_POST["extOp"]
// togther, with inner comma's and set $content.
$content = $_POST["aNumber"] . "," . $_POST["select"] . "," . $_POST["extOp"];
$j++;
}
echo $content; // echo $content which will probably echo...
// array(),array(),array() or thereabouts
?>

 

Now, some suggestions...

<?php
$content = array();
for ($i = 0; $i < count($_POST["aNumber"]); $i++) {
    $content[] = $_POST["aNumber"][$i] . "," . $_POST["select"][$i] . "," . $_POST["extOp"][$i];
}
// at this point, I'm a little unclear as to what you want to do with the extra rows.
// if I understand you, you just want to add them in a comma seperated form to the $content
// string. So...
$content = implode(",",$content);
echo $content;
?>

Ok, some points. First, two reasons your while loop didn't work. First, you were appending the the arrays together and not their individual elements (see where I add [$i] after each name). Second, you were setting $content each time through the loop, thus wiping out all previous values of $content. I decided to make $content an array (initially) so that I could then implode the final results into a string. Also, your foreach loop can be replaced by a call to the function count() which returns the number of elements in an array.

Hope all this helps! Good luck.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.