$_POST doesnt send empty checkboxgroup - php

I have been working on a contact form for a website and I got this problem:
I have 4 checkboxgroups, every each of them have at least 3 checkboxes that are available to check. We don't want them to be required to send the email. So the code is this:
$CheckboxGroup1 = array();
if(isset($_POST['submit'])){
$name = $_POST['name'];
$attending = $_POST['attending'];
$CheckboxGroup1 = isset($_POST['CheckboxGroup1']) ? $_POST['CheckboxGroup1'] : 'Nothing checked';
HTML:
<h4>What kind of set-up would you like?</h4>
<p>Additional fees may apply for living room/specialty set-ups.</p>
<p>
<div class="inline-field">
<label>
<input type="checkbox" name="CheckboxGroup1[]" value="Living Room">
Living Room
</label>
<br>
<label>
<input type="checkbox" name="CheckboxGroup1[]" value="Conference Room">
Conference Room
</label>
<br>
<label>
<input type="checkbox" name="CheckboxGroup1[]" value="Other">
Other (please specify at the end of the form)
</label>
<br>
</div>
</p>
When none of the checkboxes is selected I get the message "Nothing checked" and when one of them is selected I get the value of it. The problem is when I select more than one, I get this in my email:
What kind of set-up will you like?: Array (not the name of those selected).
I do not know what I have to change to make it work the right way.
Any help would be very much appreciated.

You cannot print array with echo. Echoing array will give you string Array. Simple way in your case to get array values is to use implode:
echo implode(', ', $yourArray);

you have to change below line
Your code
$CheckboxGroup1 = isset($_POST['CheckboxGroup1']) ? $_POST['CheckboxGroup1'] : 'Nothing checked';
Change it to
if( isset($_POST['CheckboxGroup1']))
{
$CheckboxGroup1 =implode(", ",$_POST['CheckboxGroup1']);
}
else{
$CheckboxGroup1="Nothing checked";
}

Related

SQLite statement won't take multiple values

I've looked through a lot of questions, so forgive me if there is one that may help, but I've not been able to figure this out.
So I have a simple HTML form, that takes the users input for three categories: multiplayer, platform, and genre. This is the html code
<form method="post" action="gamebuddy.php">
<div class="players">
Please select one (or both) of the following: <br>
<input type="checkbox" name="players[]" value="No">Single Player<br>
<input type="checkbox" name="players[]" value="Yes">Multiplayers<br>
</div>
<div class="platform">
Please select your game system(s): <br>
<input type="checkbox" name="platform[]" value="XBOX">Xbox<br>
<input type="checkbox" name="platform[]" value="PS3">PS3<br>
<input type="checkbox" name="platform[]" value="PC">PC<br>
<input type="checkbox" name="platform[]" value="Wii">Wii<br>
</div>
<div class="genre">
Please select the genre(s) of game you would like: <br>
<input type="checkbox" name="genre[]" value="Action" >Action<br>
<input type="checkbox" name="genre[]" value="Casual">Casual<br>
<input type="checkbox" name="genre[]" value="Roleplaying">Role-Playing<br>
<input type="checkbox" name="genre[]" value="Shooter">Shooter<br>
<input type="checkbox" name="genre[]" value="Sports">Sports<br>
</div>
<div class="submit">
<input type="submit">
</div>
And then I have a PHP file that is used when the user clicks submit. Ideally, it takes the form inputs as a variable, and uses the SQLite statement to find the games the user can play based on his choices.
Here's the PHP code:
<div class="displaygames">
Based on your choices, these games seem suitable for you: <br>
<?php
if(!empty($_POST['players'])) {
foreach($_POST['players'] as $players) {
echo $players; //echoes the value set in the HTML form for each checked checkbox.
//so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
//in your case, it would echo whatever $row['Report ID'] is equivalent to.
}
}
if(!empty($_POST['platform'])) {
foreach($_POST['platform'] as $platform) {
echo $platform; //echoes the value set in the HTML form for each checked checkbox.
//so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
//in your case, it would echo whatever $row['Report ID'] is equivalent to.
}
}
if(!empty($_POST['genre'])) {
foreach($_POST['genre'] as $genre) {
echo $genre; //echoes the value set in the HTML form for each checked checkbox.
}
}
//This is to connect to the database
$db = new SQLite3('gamebuddy.db');
//Statement that uses variables to create list
$results = $db->query("SELECT * FROM games where multiplayer = '$players' and platform = '$platform' and genre is '$genre'");
//Displays List
while ($row = $results->fetchArray()) {
echo '<ul>';
echo $row['game'];
echo '</ul>';
}
?>
So everything works fine if you put in one answer for each category (for example, the user clicks "No" to multiplayer, "PS3" to platform, and "action" to genre). BUT if the user selects "Action" AND "Role-Playing", for some reason it only takes the last one the user selects, in this instance "role-playing".
So my question is how do I get the statement to show ALL of the games when there are multiple inputs.
Thank you for your help, I will answer any questions there may be, and of course mark the answer as solved if it helps. Thanks!
If u have array in for example $players, u can use implode function and "IN" statement in SQL:
"SELECT * FROM games WHERE multiplayer IN (".implode(",", $players).")"

How do I change the country select into an input field in magento one step checkout?

In the billing_fields.phtml there is
<?php
$billingFields['country_id'] = '
<div class="input-box input-country'.((in_array('country', $formErrors)) ? ' input-error' : '').'">
<label for="billing:country_id">'.$this->__('Country').' <span class="required">*</span></label><br />
'.$this->getCountryHtmlSelect('billing').'
</div>';
?>
I do have only one country and the select-tag $this->getCountryHtmlSelect('billing') with the rendered dropdown is not user friendly as it has no further options. I feel its misleading and obsolete. My question is:
How do I have to change the code above to show my default country in a simple (not editable) input field?
EDIT
I came up with this after CBroes getCountryCollection hint
<?php
$countryCollection = $this->getCountryCollection();
foreach($countryCollection as $country) {
$country_id = $country['country_id'];
$countryName = Mage::getModel('directory/country')->load($country_id)->getName();
$billingFields['country_id'] = '
<div class="input-box input-country'.((in_array('country', $formErrors)) ? ' input-error' : '').'">
<label for="billing:country_id">'.$this->__('Country').' </label><br />
<input type="text" name="billing[country_id]" id="billing:country_id" class="input-text" value="'.$countryName.'" style="width: 83%" readonly="readonly" />
</div>';
}
?>
The frontend looks fine. Even the backend recognizes the given value. Unfortunately the emails don't. The country field remains empty there.
What am I missing or how do I make this input legit so that magento-emails accept its value?

contact form group check box array

I have a contact form built with PHP and I had a radio option box (one click) and have changed it to a group check box, which means multiple boxes can be clicked.
However, only the last most click is sent through to my email and playing with the code has messed me up, I am not very clear with the php array code and multiple (({{
Here is the html code
<label><input type="checkbox" name="addon" value="NONE" <?php if (isset($_POST['addon']) && $_POST['addon'] == 'NONE') echo 'checked="checked"'; ?> tabindex="4" /> None <br /></label>
<label><input type="checkbox" name="addon" value="HKG" <?php if (isset($_POST['addon']) && $_POST['addon'] == 'HKG') echo 'checked="checked"'; ?> tabindex="5" /> Hong Kong <br /></label>
....
<label><input type="checkbox" name="addon" value="Other Start City" <?php if (isset($_POST['trip']) && $_POST['addon'] == 'Other Start City') echo 'checked="checked"'; ?> tabindex="4" /> Other</label>
and here is the php code I have at the moment, but this only gives one answer.
$Indhold .= "Tour Extension: ".$_POST['addon']."\n";
I tried changing it to an array (as I followed the tutorial http://www.html-form-guide.com/php-form/php-form-checkbox.html) , but then only array was printed on the email.
I also want to include validation on that combi box, if possible. So they can't choose NONE and HKG, and must click at least one.
PHP only populates $_POST/GET with arrays if the name ends in [] (or [index]).
Use name="addon[]"
Arrays aren't strings, so you can't just concatenate them. You can use implode to convert the members of an array into a single string. You could also use a for loop to deal with them one by one.
You just need to handle the $_POST['addon'] as an array (after naming your checkboxes "addon[]")
// make sure at least one checkbox is checked
if (isset($_POST['addon']))
{
foreach ($_POST['addon'] as $k => $v)
{
$Indhold .= "Tour Extension: {$v}\n";
}
}
Or as an alternative:
// make sure at least one checkbox is checked
if (isset($_POST['addon']))
{
$indhold .= 'Tour Extension: ' . implode(', ', $_POST['addon']) . "\n";
}
If in the form there are multiple input elements with a single name(i.e. not followed by '[]') only the latest of all those elements can be retrieved from the submitted form. So if you check more that one checkbox in a single group(i.e. the checkboxes having a single name which is not in the format 'name[]' but simple 'name') then you can get the last checked checkbox value from the form submit because all the previously checked values in the sigle group get overwritten. Hence you need to use an array for the group name to get all the checked checkbox values in the single group.
So always use the following syntax in case you have more than one checkbox in a single group:
<input type=checkbox name="check1[]" value="v1">v1
<input type=checkbox name="check1[]" value="v2">v2
<input type=checkbox name="check1[]" value="v3">v3
<input type=checkbox name="check1[]" value="v4">v4
But in case of a single checkbox use the following:
<input type=checkbox name="check2" value="v1">v1 //No need to append square bracket at the end of the assigned name.

PHP get input , radio , selection data and insert into MySQL table

i'm new to php , i have been searching for a tutorial regarding inserting form's input(text) , radio and selection data to MySQL database's table using php. i found some tutorials but most are confusing. So i decided to ask.
Okay here's what i want to do. I have a form which have two types of input and a selection
1. input type text
2. input type radio
3. selection
Here's the HTML code :
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
<input type="submit" name="submit" value="Submit">
</form>
I have set the form action to blank because the php code will be in the same file as the HTML (it's a php file btw)
MySQL table : info
structure :
1. name
2. class
3. agree
I want the php code to insert myname into name , selection's selected data into class , radio selected data into agree
P/S Yes i have added a connect to database php script , i just want to know how to get the form data into mysql.
Can someone write a php code example on how can i do this?
Thanks and have a nice day . I hope i have provided enough information. Thanks again if you help.
1. There is a problem with your radio element. The name should be the same for both options.
It should be like this:
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
2. You can access everything in the $_POST array, since you are using the method post for the form.
$name = $_POST['myname'];
$selection = $_POST['selection'];
$agree = $_POST['agree'];
3. If you are not using parametrized SQL with a library such as PDO, MySQLi, etc... you must always escape the data, which will be used in query using mysql_real_escape_string(), in order to protect against SQL injection.
This would be a sample code, to do the escaping and the query.
// write a function somewhere, to use as a shortcut
// for escaping data which will be used in a query
function sql_escape($str){
return "'".mysql_real_escape_string($str)."'";
}
// build the query
$query = sprintf('INSERT INTO table_name(name, class, agree) VALUES(%s, %s, %s)',
sql_escape($_POST['myname']),
sql_escape($_POST['selection']),
sql_escape($_POST['agree']));
// finally run it
$result = mysql_query($query);
I've taken it a little further here, there is still plenty more that can be done and many way's to do it, for instance you could extend the $errors array to include a field id and then highlight the HTML form field so the user can see exactly where they went wrong.
Considering your form is fairly simple you would not need this.
#Shef's code would certainly do the job but I thought you might be interested in some more.
<?php
// check the form has been submitted
if (isset($_POST['submit'])) {
// escape the form fields and assign them to variables
// validate myname to ensure the user entered data
if (isset($_POST['myname']) && $_POST['myname']!='') {
$myname = mysql_real_escape_string($_POST['myname']);
} else {
// create an error variable array to store errors to display
$errors[] = 'Please enter your name';
}
// no need to validate selection here as it alway's has a value
$classtype = mysql_real_escape_string($_POST['selection']);
// validate agree unless you want to add 'checked' to one of the values
if (isset($_POST['agree']) && $_POST['agree']!='') {
$agree = mysql_real_escape_string($_POST['agree']);
} else {
$errors[] = 'Please tell us if you agree?';
}
//if errors found tell the user else write and execute the query
if ($errors) {
$message = '<p class="error">We found a problem:</p><ul>';
foreach($error as $msg){
$message .= '<li>'.$msg.'</li>';
}
$message .= '</ul><p>Please fix the error/s to continue.</p>';
} else {
// write the query
$query = "INSERT INTO table (myname, classtype, agree) VALUES ";
$query .= "('$myname','$classtype','$agree')"
// run the query
mysql_query($query);
$message = '<p class="sucessful">Thanks '.htmlspecialchars($myname).'. Your selection has been saved.</p>';
}
}
// print the message
// show the variables in the form field so they don't need re-input
if ($message!='') { echo $message; }
?>
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="<?php echo htmlspecialchars($myname) ?>" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A"<?php if ($classtype=='A') { echo ' selected'; } ?>>A</option>
<option value="B"<?php if ($classtype=='B') { echo ' selected'; } ?>>B</option>
<option value="C"<?php if ($classtype=='C') { echo ' selected'; } ?>>C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"<?php if ($agree=='Yes') { echo ' checked'; } ?>> or
<input type="radio" name="agree" value="No"<?php if ($agree=='No') { echo ' checked'; } ?>>
<input type="submit" name="submit" value="Submit">
</form>
Also: #sqwk, Don't point people towards w3schools, see this: http://w3fools.com/
Check whether there is any data in the $_POST array and get the values from it.
Have a look hereā€”the second example down is what you need: http://www.w3schools.com/php/php_mysql_insert.asp
(You do have to make the changes that Shef suggested, though.)
Also remember to check your data-integrity, otherwise people could use your insert to run malicious code.
check this simple example:
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Sname: <input type="text" name="sname" />
<input type="submit" />
</form>
after you submit form, you can take name and sname.
welcome.php::
<?php
$name= $_POST["name"];
$sname= $_POST["sname"]; ?>
now you can use this variables as if you want.

How to remember checkbox input in PHP Forms

For usability purposes I like to set up my form fields this way:
<?php
$username = $_POST['username'];
$message = $_POST['message'];
?>
<input type="text" name="username" value="<?php echo $username; ?>" />
<textarea name="message"><?php echo $message; ?></textarea>
This way if the user fails validation, the form input he entered previously will still be there and there would be no need to start from scratch.
My problem is I can't seem to keep check boxes selected with the option that the user had chosen before (when the page refreshes after validation fails). How to do this?
My first suggestion would be to use some client-side validation first. Maybe an AJAX call that performs the validation checks before continuing.
If that is not an option, then try this:
<input type="checkbox" name="subscribe" <?php echo (isset($_POST['subscribe'])?'checked="checked"':'') ?> />
So if subscribe is = 1, then it should select the box for you.
For Example, consider the following code for checkbox :-
<label for="course">Course:</label>
PHP<input type="checkbox" name="course[]" id="course" <?php if ((!empty($_POST["course"]) && in_array("PHP", $_POST["course"]))) {
echo "checked";
} ?> value="PHP" />
Then, this would remember the checkbox of "PHP" if it is checked, even if the validation for the page fails and so on for "n" number of checkboxes as shown below:-
<label for="course">Course:</label>
PHP<input type="checkbox" name="course[]" id="course" <?php if ((!empty($_POST["course"]) && in_array("PHP", $_POST["course"]))) {
echo "checked";
} ?> value="PHP" />
HTML<input type="checkbox" name="course[]" id="course" <?php if ((!empty($_POST["course"]) && in_array("HTML", $_POST["course"]))) {
echo "checked";
} ?> value="HTML" />
CSS<input type="checkbox" name="course[]" id="course" <?php if ((!empty($_POST["course"]) && in_array("CSS", $_POST["course"]))) {
echo "checked";
} ?> value="CSS" />
Javascript<input type="checkbox" name="course[]" id="course" <?php if ((!empty($_POST["course"]) && in_array("Javascript", $_POST["course"]))) {
echo "checked";
} ?> value="Javascript" />
And most importantly, do not forget to declare the "course" variable as an array at the start of the code as shown below :-
$course = array();
I have been battling how to create sticky check box (that is able to remember checked items any time you visit the page). Originally, I get my values from a database table. This means that my check box value is entered to a column on my db table.
I created the following code and it works just fine. I did not want to go through that whole css and deep coding, so...
CODE IN PHP
$arrival = ""; //focus here.. down
if($row['new_arrival']==1) /*new_arrival is the name of a column on my table that keeps the value of check box*/
{$arrival="checked";}// $arrival is a variable
else
{$arrival="";};
echo $arrival;
<b><label for ="checkbox">New Arrival</label></b>
<input type="checkbox" name ="$new_arrival" value="on" '.$arrival.' /> (Tick box if product is new) <BR><BR>
<input type="checkbox" name="somevar" value="1" <?php echo $somevar ? 'checked="checked"' : ''; ?>/>
Also, please consider sanitising your inputs, so instead of:
$somevar = $_POST['somevar'];
...it is better to use:
$somevar = htmlspecialchars($_POST['somevar']);
When the browser submits a form with a checked checkbox, it sends a variable with the name from the name attribute and a value from the value attribute. If the checkbox is not checked, the browser submits nothing for the checkbox. On the server side, you can handle this situation with array_key_exists(). For example:
<?php
$checkedText = array_key_exists('myCheckbox', $_POST) ? ' checked="checked"' : '';
?>
<input type="checkbox" name="myCheckbox" value="1"<?php echo $checkedText; ?> />
Using array_key_exist() avoids a potential array index undefined warning that would be issued if one tried to access $_POST['myCheckbox'] and it didn't exist.
You may add this to your form:
<input type="checkbox" name="mycheckbox" <?php echo isset($_POST['mycheckbox']) ? "checked='checked'" : "" ?> />
isset checks if a variable is set and is not null. So in this code, checked will be added to your checkbox only if the corresponding $_POST variable has a value..
My array has name="radioselection" and value="1", value="2", and value="3" respectively and is a radio button array... how to I check if the radio value is selected using this code
I tried:
<?php echo (isset($_POST['radioselection']) == '1'?'checked="checked"':'') ?> />

Categories