Tycoon Talk
Become a Big fish!
The number 1 forum for online business!
Post topics, ask questions, share your knowledge.
Tycoon Talk is part of Freelancer.com - find skilled workers online at a fraction of the cost.

PHP Forum


You are currently viewing our PHP Forum as a guest. Please register to participate.
Login



Freelance Jobs

Reply
Problems with multiple checkboxes in PHP form
Old 06-13-2011, 06:10 PM Problems with multiple checkboxes in PHP form
Average Talker

Posts: 16
Name: Jen Starbuck
Trades: 0
Hi,

I am a beginner with PHP and am trying to fix a form on my website. The problem is with a question allowing multiple checkbox selections. I would like a list of all the checkboxes checked to show in the email I receive. How can I fix this? Right now it only shows the word 'Array.'

Thanks in advance for your help!

Here's my code:

<input type="checkbox" class="statezip" name="interestedin[]" value="Buying" /> Buying a property<br />
<input type="checkbox" class="statezip" name="interestedin[]" value="Selling" /> Selling a property<br />
<input type="checkbox" class="statezip" name="interestedin[]" value="Career Opportunity" /> Career opportunities<br />
<input type="checkbox" class="statezip" name="interestedin[]" value="Other" /> Other<br />
</select>


<?php
/* Set e-mail recipient */
$myemail = "jenstarbuck@gmail.com";

/* Check all form inputs using check_input function */
$name = check_input($_POST['name'], "Please enter your name");
$email = check_input($_POST['email'], "Please enter your email address");
$phone = check_input($_POST['phone']);
$address = check_input($_POST['address']);
$city = check_input($_POST['city']);
$state = check_input($_POST['state']);
$zip = check_input($_POST['zip']);
$contactmethod = check_input($_POST['contactmethod']);
$interestedin = check_input($_POST['interestedin']);
$comments = check_input($_POST['comments'], "Please let us know how we can help");
$subject = "Starbuck Realty Group - Website Contact";

/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address not valid");
}

/* Let's prepare the message for the e-mail */
$message = "Hello!

Your contact form has been submitted by:

Name: $name
E-mail: $email
Phone: $phone

Address: $address
City: $city
State: $state
Zipcode: $zip

Preferred method of contact: $contactmethod

Interested in: $interestedin
Comments: $comments

End of message
";

/* Send the message using mail() function */
mail($myemail, $subject, $message);

/* Redirect visitor to the thank you page */
header('Location: contactthankyou.html');
exit();

/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}

function show_error($myError)
{
?>
<html>
<body>

<b>Please correct the following error:</b><br />
<?php echo $myError; ?>

</body>
</html>
<?php
exit();
}
?>
jstarbuck is offline
Reply With Quote
View Public Profile
 
 
Register now for full access!
Old 06-13-2011, 06:14 PM Re: Problems with multiple checkboxes in PHP form
chrishirst's Avatar
Missing! presumed drunk.

Posts: 42,384
Name: Chris Hirst
Location: Blackpool. UK
Trades: 0
Get rid of the "[]" and the "interestedin" will be a comma seperated string of selected values when submitted.
__________________
Chris. ->>
Please login or register to view this content. Registration is FREE
<<-

A foolish consistency is the hobgoblin of little minds
Thought for today:- Is SEO the only industry where all the cowboys are Indians?
chrishirst is offline
Reply With Quote
View Public Profile Visit chrishirst's homepage!
 
Old 06-13-2011, 06:31 PM Re: Problems with multiple checkboxes in PHP form
Average Talker

Posts: 16
Name: Jen Starbuck
Trades: 0
When I remove the [] it then only shows the value of the last checkbox selected (not the values of all the checkboxes selected). I would like to see a list of all the checkboxes selected.
jstarbuck is offline
Reply With Quote
View Public Profile
 
Old 06-13-2011, 06:40 PM Re: Problems with multiple checkboxes in PHP form
chrishirst's Avatar
Missing! presumed drunk.

Posts: 42,384
Name: Chris Hirst
Location: Blackpool. UK
Trades: 0
how are you submitting the form

there are no form tags, no submit botton and a stray closing select tag in your code?


Is that ALL the code?
__________________
Chris. ->>
Please login or register to view this content. Registration is FREE
<<-

A foolish consistency is the hobgoblin of little minds
Thought for today:- Is SEO the only industry where all the cowboys are Indians?
chrishirst is offline
Reply With Quote
View Public Profile Visit chrishirst's homepage!
 
Old 06-13-2011, 06:41 PM Re: Problems with multiple checkboxes in PHP form
mgraphic's Avatar
Truth Seeker

Latest Blog Post:
JAMISONTUNES
Posts: 2,918
Name: Keith Marshall
Location: Connecticut
Trades: 0
$interestedin = check_input(implode(', ', (array)$_POST['interestedin']));
__________________

<mgraphic /> - I don't have a solution but I admire the problem.
mgraphic is offline
Reply With Quote
View Public Profile
 
Old 06-13-2011, 06:42 PM Re: Problems with multiple checkboxes in PHP form
Average Talker

Posts: 16
Name: Jen Starbuck
Trades: 0
This is the coding for the form on contact.html:

HTML Code:
<div class="contact_form">
<p>How can we help?  Please fill out the form below and a member of our team will be in touch with you soon: (*required)</p>
                 
    <form action="contact.php" method="post" >
      <table width="100%" border="0" cellspacing="0" cellpadding="0" class="tblForm">
      <tr>
        <td colspan="2" style="height: 10px;"></td>
      </tr>
      <tr>
        <td width="" valign="top" class="field_text">*Name:</td>
        <td width="" valign="top">
          <input type="text" class="form_field" name="name"></td>
      </tr>
      <tr>
        <td valign="top" class="field_text">*Email: </td>
        <td valign="top">
          <input type="text" class="form_field" name="email">
        </td>
      </tr>
      <tr>
        <td valign="top" class="field_text">Phone: </td>
        <td valign="top">
        <input type="text" class="form_field" name="phone"></td>
      </tr>
      <tr>
        <td valign="top" class="field_text">Address:</td>
        <td valign="top">
        <input type="text" class="form_field" name="address"></td>
      </tr>
      <tr>
        <td valign="top" class="field_text">City:</td>
        <td valign="top">
          <input type="text" class="form_field" name="city"></td>
      </tr>
      <tr>
        <td valign="top" class="field_text">State:</td>
        <td valign="top">
          <select name="state" class="statezip">
            <option value="" selected>
            <option value="AL">Alabama
              <option value="AK">Alaska
                <option value="AZ">Arizona
                  <option value="AR">Arkansas
                    <option value="CA">California
                      <option value="CO">Colorado
                        <option value="CT">Connecticut
                        <option value="DE">Delaware
                        <option value="FL">Florida
                        <option value="GA">Georgia
                        <option value="HI">Hawaii
                        <option value="ID">Idaho
                        <option value="IL">Illinois
                        <option value="IN">Indiana
                        <option value="IA">Iowa
                        <option value="KS">Kansas
                        <option value="KY">Kentucky
                        <option value="LA">Louisiana
                        <option value="ME">Maine
                        <option value="MD">Maryland
                        <option value="MA">Massachusetts
                        <option value="MI">Michigan
                        <option value="MN">Minnesota
                        <option value="MS">Mississippi
                        <option value="MO">Missouri
                        <option value="MT">Montana
                        <option value="NE">Nebraska
                        <option value="NV">Nevada
                        <option value="NH">New Hampshire
                        <option value="NJ">New Jersey
                        <option value="NM">New Mexico
                        <option value="NY">New York
                        <option value="NC">North Carolina
                        <option value="ND">North Dakota
                        <option value="OH">Ohio
                        <option value="OK">Oklahoma
                        <option value="OR">Oregon
                        <option value="PA">Pennsylvania
                        <option value="RI">Rhode Island
                        <option value="SC">South Carolina
                        <option value="SD">South Dakota
                        <option value="TN">Tennessee
                        <option value="TX">Texas
                        <option value="UT">Utah
                        <option value="VT">Vermont
                        <option value="VA">Virginia
                        <option value="WA">Washington
                        <option value="DC">Washington D.C.
                        <option value="WV">West Virginia
                        <option value="WI">Wisconsin
                        <option value="WY">Wyoming
                      </select>
        </td>
      </tr>
      <tr>
        <td valign="top" class="field_text">Zipcode: </td>
        <td valign="top">
        <input name="zip" class="statezip" type="text" size="10"></td>
      </tr>


      <tr>
        <td valign="top" class="field_text">Preferred method of contact: </td>
       <td valign="top">
          <select name="contactmethod" class="statezip">
            <option value=""></option>
            <option value="Phone">Phone</option>
             <option value="Email">Email</option>
                    </select>
        </td>
      </tr>

       <tr>
        <td valign="top" class="field_text">Interested in: </td>
       <td valign="top">
            <input type="checkbox" class="statezip" name="interestedin" value="Buying" /> Buying a property<br />
            <input type="checkbox" class="statezip" name="interestedin" value="Selling" /> Selling a property<br />
            <input type="checkbox" class="statezip" name="interestedin" value="Career Opportunity" /> Career opportunities<br />
            <input type="checkbox" class="statezip" name="interestedin" value="Other" /> Other<br />             
                    </select>
        </td>
      </tr>
      
   

 

        <tr>        
                <td valign="top" class="field_text" style="padding-top: 15px;">Questions, comments, or other information to help us better serve you:</td> 
                <td valign="top"><textarea name="comments" rows="10" cols="31" class="statezip"></textarea></td>
            </tr>
            
      <tr>
        <td></td>   
        <td>

          <input type="submit" value="Submit">
          <input type="reset" value="Clear Form">
        </td>
      </tr>
      <tr>
        <td colspan="2" style="height: 10px;"></td>
      </tr>
    </table>
    </form></div>

Last edited by chrishirst; 06-13-2011 at 06:45 PM..
jstarbuck is offline
Reply With Quote
View Public Profile
 
Old 06-13-2011, 06:46 PM Re: Problems with multiple checkboxes in PHP form
Average Talker

Posts: 16
Name: Jen Starbuck
Trades: 0
Quote:
Originally Posted by mgraphic View Post
$interestedin = check_input(implode(', ', (array)$_POST['interestedin']));
This did the trick! Thank you SOOOOOOOOO much!
jstarbuck is offline
Reply With Quote
View Public Profile
 
Old 08-29-2011, 05:26 AM Re: Problems with multiple checkboxes in PHP form
Novice Talker

Posts: 6
Trades: 0
Hello mgraphic (and all the other experienced programmers),

I try to follow your advise, but I fail to have a message send with the checked boxes. I translated my form and shortened it, but in essence I tryed to copy the idea; but I will have forgotten something:

In the HTML:

HTML Code:
<form name="form" method="post" action="thanx.php">
<input type="checkbox" name="activities[]" value="sports" />sports<br/>
<input type="checkbox" name="activities[]" value="travel" />travel<br />
<input type="checkbox" name="activities[]" value="gaming" />gaming<br />
 <input type="submit" name="Submit" value="Send"/>
  </form>
PHP Code:
<?php

$activities 
check_input(implode(', ', (array)$_POST['activities']));

$message "Activities: $activities";

mail('my_mail_address''Form'$message);  
  
?>
Will you please give me some advise?

Wouter
WouterL is offline
Reply With Quote
View Public Profile
 
Old 08-29-2011, 07:35 AM Re: Problems with multiple checkboxes in PHP form
lizciz's Avatar
Super Spam Talker

Posts: 807
Name: Mattias Nordahl
Location: Sweden
Trades: 0
Do you actually have a function called check_input(), or did you just copy it directly from the previous post?
__________________
Your answers will only be as good as your question. Formulate it well and give all the necessary information.
lizciz is online now
Reply With Quote
View Public Profile Visit lizciz's homepage!
 
Old 08-29-2011, 07:49 AM Re: Problems with multiple checkboxes in PHP form
Novice Talker

Posts: 6
Trades: 0
As a beginner I simply copied it, because I thought is was a smart php-function .
Can you help me to correct it?

With kind regards, Wouter

Last edited by WouterL; 08-29-2011 at 08:13 AM..
WouterL is offline
Reply With Quote
View Public Profile
 
Old 08-29-2011, 11:16 AM Re: Problems with multiple checkboxes in PHP form
vectorialpx's Avatar
Extreme Talker

Posts: 249
Name: octavian
Location: Bucharest
Trades: 0
When submitting one or more fields with the name someField[] (GET or POST) you will have to work with $_POST['someField'] or $_GET['someField'] as array

WouterL, what do you need to check?
You can have
Code:
function checkActivities($postValue) {
    if(!is_array($postValue)) return false;
    if(!empty(array_diff($postValue, array('someSport', 'tennis', 'bowling', 'footbal'))) {
        return false;
    }
    return true;
}

// remember, $_POST['activities'] must be an array
if(!checkActivities($_POST['activities'])) {
    die('please don\'t hack me');
} else {
    $mailContent = 'Activities: ' . implode(', ', $_POST['activities']);
}
mail('your@mail.com' , 'subject of mail' ,$mailContent);
__________________
you can
Please login or register to view this content. Registration is FREE

Last edited by vectorialpx; 08-29-2011 at 11:19 AM..
vectorialpx is offline
Reply With Quote
View Public Profile Visit vectorialpx's homepage!
 
Old 08-29-2011, 11:40 AM Re: Problems with multiple checkboxes in PHP form
Novice Talker

Posts: 6
Trades: 0
Thank you for helping me. I tried to put the script in my (Dreamweaver) testscript,
but there was immediatly a call for a syntaxis error in the line with "ifempty(array..."

Ok, I found out that one ')' was missing. I'll try again:

HTML Code:
<html>
<head>
<title>test</title>
</head>

<body>
<form name="form" method="post" action="thanx.php">
<input type="checkbox" name="activities[]" value="sports" />sports<br/>
<input type="checkbox" name="activities[]" value="travel" />travel<br />
<input type="checkbox" name="activities[]" value="gaming" />gaming<br />
 <input type="submit" name="Submit" value="Send"/>
  </form>
PHP Code:
<?php

 
function checkActivities($postValue) {
    if(!
is_array($postValue)) return false;
    if(!empty(
array_diff($postValue, array('sport''travel''gaming', )))  )  {
        return 
false;
    }
    return 
true;
}

// remember, $_POST['activities'] must be an array
if(!checkActivities($_POST['activities'])) {
    die(
'please don\'t hack me');
} else {
    
$mailContent 'Activities: ' implode(', '$_POST['activities']);
}
mail('your@mail.com' 'subject of mail' ,$mailContent);

?>
HTML Code:
</body>
</html>
Well, it's not enough... My form doesn't show up in the browser (and it does when I let the php-part out).

I hope you can help me another step forward.

Last edited by WouterL; 08-30-2011 at 03:21 AM..
WouterL is offline
Reply With Quote
View Public Profile
 
Old 08-30-2011, 04:09 AM Re: Problems with multiple checkboxes in PHP form
vectorialpx's Avatar
Extreme Talker

Posts: 249
Name: octavian
Location: Bucharest
Trades: 0
I just gave you an example, you have to adapt it
I think now you get the "please don't hack me message"

instead of
Code:
if(!checkActivities($_POST['activities'])) {
    die('please don\'t hack me');
} else {
    $mailContent = 'Activities: ' . implode(', ', $_POST['activities']);
}
mail('your@mail.com' , 'subject of mail' ,$mailContent);
you need another condition on the top

PHP Code:
if(isset($_POST['activities']) && is_array($_POST['activities'])) {
if(!
checkActivities($_POST['activities'])) {
    die(
'please don\'t hack me');
} else {
    
$mailContent 'Activities: ' implode(', '$_POST['activities']);
}
mail('your@mail.com' 'subject of mail' ,$mailContent);
} else {
echo 
'Send the form first.';

As you may know, 'die' will stop the script so you don't need that in real life, you have to make a more user-friendly thing, like a redirect to a "thank you page".
__________________
you can
Please login or register to view this content. Registration is FREE

Last edited by vectorialpx; 08-30-2011 at 04:11 AM..
vectorialpx is offline
Reply With Quote
View Public Profile Visit vectorialpx's homepage!
 
Old 08-30-2011, 05:53 AM Re: Problems with multiple checkboxes in PHP form
Novice Talker

Posts: 6
Trades: 0
When I replace your last code I still see no form on my internetpage.

With only the last code as php I can see and fill in the form (with the text "Send the form first."), but I don't receive mail when I check a box (of course I have put my own email address in).
And when I don't check any box, I also only go to the thanx.php and get no mean message on my screen.
So there must be something wrong in the first part of the php code; sorry, I'm not able to correct this myself...

I'll put the complete form here (the last complete version that don't show up when it's uploaded):

<html>
<head>
<title>test</title>
</head>

<body>
<form name="form" method="post" action="thanx.php">
<input type="checkbox" name="activities[]" value="sports" />sports<br/>
<input type="checkbox" name="activities[]" value="travel" />travel<br />
<input type="checkbox" name="activities[]" value="gaming" />gaming<br />
<input type="submit" name="Submit" value="Send"/>
</form>
PHP Code:
<?php

 
function checkActivities($postValue) {
    if(!
is_array($postValue)) return false;
    if(!empty(
array_diff($postValue, array('sports''travel''gaming')))  )  {
        return 
false;
    }
    return 
true;
}

if(isset(
$_POST['activities']) && is_array($_POST['activities'])) {
if(!
checkActivities($_POST['activities'])) {
    die(
'Please try again, you can do it!');
} else {
    
$mailContent 'Activities: ' implode(', '$_POST['activities']);
}
mail('wiped@out.nl' 'Activities' ,$mailContent);
} else {
echo 
'Send the form first.';
}  
?>
</body>
</html>

Last edited by WouterL; 08-30-2011 at 01:20 PM..
WouterL is offline
Reply With Quote
View Public Profile
 
Old 08-30-2011, 07:16 AM Re: Problems with multiple checkboxes in PHP form
vectorialpx's Avatar
Extreme Talker

Posts: 249
Name: octavian
Location: Bucharest
Trades: 0
If you are running on localhost, you need a mail server

make the line
mail('wlooman@xs4all.nl' , 'Activities' ,$mailContent);

like
if(@mail('wlooman@xs4all.nl' , 'Activities' ,$mailContent))
{ echo 'mail send!'; } else { echo 'cannot send mail!'; }
__________________
you can
Please login or register to view this content. Registration is FREE
vectorialpx is offline
Reply With Quote
View Public Profile Visit vectorialpx's homepage!
 
Old 08-30-2011, 07:31 AM Re: Problems with multiple checkboxes in PHP form
Novice Talker

Posts: 6
Trades: 0
Hi, I have a external server that works fine with php en forms. So far I know what I'm doing.

It's just the checkboxes that don't do what I want. And it is very difficult to find a solution on the internet: I studied over 40 googled pages about textboxes and mailforms, and I tried a lot of code, but without succes.

Maybe you'd better try my/your code yourself: it's a complete script you can paste and test (local or extern, with your own mail address ).

At last I succeded! With a script on another site... I tell you later, have to go now.
And answer lizciz beneath.

Last edited by WouterL; 08-30-2011 at 09:15 AM..
WouterL is offline
Reply With Quote
View Public Profile
 
Old 08-30-2011, 07:45 AM Re: Problems with multiple checkboxes in PHP form
lizciz's Avatar
Super Spam Talker

Posts: 807
Name: Mattias Nordahl
Location: Sweden
Trades: 0
Add some debugging, to see what is actually going on. For example, check the values of $_POST['activities'] and $mailContent.

PHP Code:
var_dump($_POST['activities'], $mailContent); 

EDIT: Oh and by the way, the checkActivities() function that vectorialpx supplied requires all checkboxes to be marked. Did you try marking all of them?
__________________
Your answers will only be as good as your question. Formulate it well and give all the necessary information.

Last edited by lizciz; 08-30-2011 at 07:50 AM..
lizciz is online now
Reply With Quote
View Public Profile Visit lizciz's homepage!
 
Old 08-30-2011, 10:33 AM Re: Problems with multiple checkboxes in PHP form
vectorialpx's Avatar
Extreme Talker

Posts: 249
Name: octavian
Location: Bucharest
Trades: 0
Looks like I got an error

!empty(array_diff( ... )) is not a valid thing

PHP Code:
<?php
# let's say we have a POST
$_POST['activities'][] = 'travel';

 function 
checkActivities($postValue) {
    if(!
is_array($postValue)) return false;
    if(
array_diff($postValue, array('sports''travel''gaming')) != array()  )  {
        return 
false;
    }
    return 
true;
}

if(isset(
$_POST['activities']) && is_array($_POST['activities'])) {
if(!
checkActivities($_POST['activities'])) {
    die(
'Please try again, you can do it!');
} else {
    
$mailContent 'Activities: ' implode(', '$_POST['activities']);
}
# mail('wlooman@xs4all.nl' , 'Activities' ,$mailContent);
echo 'send mail';
} else {
echo 
'Send the form first.';
}
?>

Quote:
Oh and by the way, the checkActivities() function that vectorialpx supplied requires all checkboxes to be marked
No.
If array_diff ( fromSomeValues , someValidValues ) is not empty
than the array 'fromSomeValues' has some invalid value
__________________
you can
Please login or register to view this content. Registration is FREE
vectorialpx is offline
Reply With Quote
View Public Profile Visit vectorialpx's homepage!
 
Old 08-30-2011, 01:19 PM Re: Problems with multiple checkboxes in PHP form
Novice Talker

Posts: 6
Trades: 0
Ok, my checkbox form works . I show here the simple example (but it also goes well in my own large form).

I use two documents. The first is activities.html with the
HTML Code:
<html>
<head>
<title>Activities Form</title>
</head>

<body>
<form name="form" method="post" action="mail.php">
<input type="checkbox" name="activities[]" value="sports" />sports<br/>
<input type="checkbox" name="activities[]" value="travel" />travel<br />
<input type="checkbox" name="activities[]" value="gaming" />gaming<br />
 <input type="submit" name="submit" value="Send"/>
  </form>

</body>
</html>
As you see it directs to the file mail.php with

PHP Code:
<?php
if(isset($_POST['submit'])) {  //Attention: when 'submit'  is not written exactly as in het form itself - e.g. name="Submit" -, it won't work! 

    
$to "mail@somewhere.nl"//Put here your own email address
    
$subject "Activities Form"//The name is free to choose
    
    
foreach($_POST['activities'] as $value) { //The name of the checkbox without []
        
$activities_msg .= "Checked: $value\n"//Again that name and an extension.
    
}
    
    
$body $activities_msg "//Of course you can make the body larger with other variables and plain text.

    
echo "Form has been sent";
    
mail($to$subject$body);
    
} else {
    echo 
"Ooops!";
}
?>
Thanks a lot for all help!

PS The next question is how to get a maximum checked boxes (3 out of 20). I hope I can find that myself, but I'll come back here to see if there is a solution presented .
WouterL is offline
Reply With Quote
View Public Profile
 
Old 08-30-2011, 03:25 PM Re: Problems with multiple checkboxes in PHP form
lizciz's Avatar
Super Spam Talker

Posts: 807
Name: Mattias Nordahl
Location: Sweden
Trades: 0
Quote:
Originally Posted by WouterL View Post
PS The next question is how to get a maximum checked boxes (3 out of 20). I hope I can find that myself, but I'll come back here to see if there is a solution presented .
You can check the size of the array, count().
__________________
Your answers will only be as good as your question. Formulate it well and give all the necessary information.
lizciz is online now
Reply With Quote
View Public Profile Visit lizciz's homepage!
 
Reply     « Reply to Problems with multiple checkboxes in PHP form
 

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off





   
RSS Feed  Feeds: RSS   JS   XML
RSS Feed  Feeds for this forum: RSS   JS   XML



Page generated in 0.97488 seconds with 12 queries