PHP checkbox post if selected some two element get no result - javascript

I have created a jquery code for my checkbox. My jquery codes working like this. If user checked some two checkboxes then I give alert like alert("You can not select this two checkbox");
$("body").on("click", ".submit", function(){
var lookChecked = $('#c').is(':checked');
var lookCheckedTwo = $("#java").is(':checked');
var lookCheckedTree = $("#php").is(':checked');
var lookCheckedFour = $("#html").is(":checked");
var lookCheckedFive = $("#unix").is(":checked");
if(lookChecked && lookCheckedTwo || lookChecked && lookCheckedTree) {
alert("You can not select #c and #java or #c and #php at the same time");
}
});
This is working fine. But I want to check it also with PHP
if(isset($_POST['submit'])){
if(!empty($_POST['check_list'])) {
// Seçimlerin toplamını kontrol et
$checked_count = count($_POST['check_list']);
if($checked_count >=3) {
echo "You can not select ".$checked_count." ";
}else{
echo "".$checked_count." checkbox result for: <br/>";
foreach($_POST['check_list'] as $selected) {
echo "<p>".$selected ."</p>";
}
}
}
else{
echo "<b>Please select a checkbox</b>";
}
}
HTML
<form action="index.php" method="post">
<label class="heading">Select your categories:</label>
<input type="checkbox" name="check_list[]" id="c" value="C/C++"><label>C/C++</label>
<input type="checkbox" name="check_list[]" id="java" value="Java"><label>Java</label>
<input type="checkbox" name="check_list[]" id="php" value="PHP"><label>PHP</label>
<input type="checkbox" name="check_list[]" id="html" value="HTML/CSS"><label>HTML/CSS</label>
<input type="checkbox" name="check_list[]" id="unix" value="UNIX/LINUX"><label>UNIX/LINUX</label>
<input type="submit" class="submit" name="submit" Value="Submit"/>
<!----- Including PHP Script ----->
<?php include 'checkbox_value.php';?>
</form>
So what I want to do with PHP. If the user checked C/C++ and Java same time. I want to show a just warning. (No result for C/C++ and Java please select another category) or if the user selected PHP and Unix (No result for PHP and Unix please select another category). How can I do that with PHP

if (in_array("C/C++", $_POST['check_list']) && in_array("Java", $_POST['check_list'])){
echo "No result for C/C++ and Java please select another category";
}else{
if (in_array("PHP", $_POST['check_list']) && in_array("Unix", $_POST['check_list']))
{
echo "No result for PHP and Unix please select another category";
}
}

The best way is when you change your input name like this:
<input type="checkbox" name="check_list[cc]" id="c" value="C/C++"><label>C/C++</label>
<input type="checkbox" name="check_list[java]" id="java" value="Java"><label>Java</label>
Than check it with PHP
if( isset($_POST['check_list']['cc'],$_POST['check_list']['java']) OR
isset($_POST['check_list']['php'],$_POST['check_list']['html']) ){
echo "You check PHP & HTML or C++ & Java";
} else if( empty($_POST['check_list']) ) {
echo "Please select a checkbox";
} else {
echo "Please select C/C++ & Java or PHP & Java";
}

Related

How to get answer from two checked checkboxes in PHP

I have these pages:
secondpage.php
<center>
Go back
<form action="fourthpage.php" method="POST">
<select name="what" class="what" required oninvalid="this.setCustomValidity('Please enter what are you paying for ')" oninput="setCustomValidity('')" />
<option value="" disabled selected>Choose what you are paying for</option>
<option>Something</option>
<option>Something</option>
<option>Something</option>
<option>Something</option>
</select>
<br>
<button>other...</button>
<br><br>
<label for="price">Type the price</label>
<br>
<input id="amount" name="price" placeholder="&#8364" required oninvalid="this.setCustomValidity('Please enter the price ')" oninput="setCustomValidity('')" / type="number">
<br><br>
<label for="payment">Who has to pay for it:</label>
<br>
<label for="everybody">Everybody</label>
<input name="check_list[]" class="everybody" type="checkbox" value="everybody" onclick="ckChange(this)" required>
&nbsp&nbsp
<label for="John">John</label>
<input name="check_list[]" class="John" type="checkbox" value="John" required>
&nbsp&nbsp
<label for="Peter">Peter</label>
<input name="check_list[]" class="denis" type="checkbox" value="Peter" required>
&nbsp&nbsp
<label for="Ferrari">Ferrari</label>
<input name="check_list[]" class="Ferrari" type="checkbox" value="Ferrari" required>
<br>
<input type="submit" name="submit" value="SEND">
</form>
</center>
fourthpage.php
<table>
<center><h1>John</h1></center>
<tr><td>WHO </td><td>WHAT </td><td>HOW MUCH</td><td>MY DEBT</td><td>TOTAL DEBT</td></tr>
<tr><td class="d"><?php if(isset($_POST['submit'])){//to run PHP script on submit
if(!empty($_POST['check_list'])){
// Loop to store and display values of individual checked checkbox.
foreach($_POST['check_list'] as $selected){
echo $selected."</br>";
}}} ?></td>
<td class="r"><?php if (isset($_POST['submit'])) { echo $_POST["what"];} ; ?></td>
<td class="a"><?php if (isset($_POST['submit'])) { echo $_POST["price"];} ; ?></td>
<td class="debt"><?php if(isset($_POST['submit'])){//to run PHP script on submit
if(!empty($_POST['check_list'])){
// Loop to store and display values of individual checked checkbox.
foreach($_POST['check_list'] as $selected){
if ($selected == 'everybody'){ echo $_POST["price"]/4;}
elseif ($selected == 'John' || 'Peter' || 'Ferrari'){ echo $_POST["price"]/2;}
elseif ($selected == 'John' && $selected == 'Peter') { echo $_POST["price"]/3;} ;
}}}?> </td></tr>
<td class="total"><?php if (isset($_POST['submit'])) { ;} ; ?></td></tr>
</table>
<button onClick="location.reload();location.href='secondpage.php'">ADD</button> <button>PAY</button></center>
and javascript
function ckChange(el) {
var ckName = document.getElementsByName(el.name);
if (el.checked) {
for (var i = 0; i < ckName.length; i++) {
ckName[i].disabled = ckName[i] !== el;
}
} else {
for (var i = 0; i < ckName.length; i++) {
ckName[i].disabled = false
}
}
}
$(function(){
var requiredCheckboxes = $(':checkbox[required]');
requiredCheckboxes.change(function(){
if(requiredCheckboxes.is(':checked')) {
requiredCheckboxes.removeAttr('required');
}
else {
requiredCheckboxes.attr('required', 'required');
}
});
});
When i try to get the answer of 2 checked checkboxes like
elseif ($selected == 'John' && $selected == 'Peter') { echo $_POST["price"]/3;}
it doesn't give me the right answer. I don't get the price divided by 3. For example: i chose the price 15 and under debt should be 15/3 = 5. Instead of 5 i get 7.5 7.5. Any solutions?
The problem not just in
elseif ($selected == 'Jacopo' && 'Denis' && 'Angus'){ echo $_POST["price"]/2;}
So first you want to know that this line must wrote like this.
elseif ($selected == 'Jacopo' || $selected == 'Denis' || $selected == 'Angus'){ echo $_POST["price"]/2;}
And Second you don't want to use another foreach. we want to make sure that the elements you're looking for inside the check_list array, So you can use in_array() function.
This is your final code.
<td class="debt"><?php
if(isset($_POST['submit'])){
if(!empty($_POST['check_list'])){
if (in_array('everybody', $_POST['check_list'])){ echo $_POST["price"]/4;}
elseif (in_array('Jacopo', $_POST['check_list']) && in_array('Denis', $_POST['check_list'])) { echo $_POST["price"]/3;}
elseif (in_array('Jacopo', $_POST['check_list']) || in_array('Denis', $_POST['check_list']) || in_array('Angus', $_POST['check_list'])){ echo $_POST["price"]/2;}
}
}
?></td>
I hope everything is clear and i hope i helped you.
I think you want it like this (correct me if not):
if "everybody" was checked, case 1
if ALL THREE (respectively TWO) boxes with names are checked, cases 2 or 3
any other combination will be ignored
In this case you must ensure, that $_POST['check_list'] has all the required items checked and nothing more. Please consider the following example:
// to play around with...
$_POST['check_list'] = ['everybody', 'Jacopo', 'Denis'];
$case1 = ['everybody'];
$case2 = ['Jacopo', 'Denis', 'Angus'];
$case3 = ['Jacopo', 'Denis'];
$result1 = array_intersect($_POST['check_list'], $case1);
$result2 = array_intersect($_POST['check_list'], $case2);
$result3 = array_intersect($_POST['check_list'], $case3);
if (count($case1) == count($result1)) {
echo 'case 1';
}
elseif (count($case2) == count($result2)) {
echo 'case 2';
}
elseif (count($case3) == count($result3)) {
echo 'case 3';
}
The array_intersect will compare all arrays to find things in common. Anything that is not in any of the other arrays will be removed. Set theory.
edit: fixed typos

PHP form text field to mysql based on selected checkbox [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am trying to create sign up form, where it has multiple text field (name, email, phone, ..) and have multiple checkbox options.
I also created multiple tables in mysql database, one for each checkbox.
My goal is to store values in text field to selected checkbox data table.
My question is how can I create if statement to look what checkbox is selected, so it will store input of text field to that table
input.php
<html>
<head>
</head>
<script type="text/javascript">
function toggle(source) {
checkboxes = document.getElementsByName('chk1[]');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
<body>
<h2><font color="white">Welcome to Cars and Coffee</h2>
<p>Sign up to receive if you are interested in
receiving information from Cars and Coffee.</p>
<p>Please select at least one option</p>
<form name="newEntry" action="page.php" method="POST">
name<input type=text length=60 size=30 name="name"><br>
email<input type=text length=60 size=30 name="email"><br>
car<input type=text length=60 size=30 name="car"><br>
phone<input type=text length=60 size=30 name="phone"><br>
<input type="submit" name="submit" email="add" car="add" phone="add" >
</form>
<form action="page.php" method="POST">
<input type="checkbox" name="chk[]" value="cars_coffee">Cars & Coffee<br>
<input type="checkbox" name="chk[]" value="kentucky">Kentucky Derby Party<br>
<input type="checkbox" name="chk[]" value="july">July 4th<br>
<input type="checkbox" name="chk[]" value="labor">Labor Day<br>
<input type="checkbox" name="chk[]" value="new_year">New Years Day<br>
<input type="checkbox" name="chk[]" value="all" onClick="toggle(this)">Select All<br>
</form>
<?php
mysql_connect("localhost", "db", "pw");
mysql_select_db("db");
$qh = mysql_query("select * from all_emails order by id desc");
if (#mysql_num_rows($qh)) { /* the if(#...) syntax makes PHP supress any
warnings that might come out of that function. */
/* mysql_fetch_object(query handle);
* returns an object whose contents are that of one rotw in the
database. */
while ($obj = mysql_fetch_object($qh)) {
echo "
<p>
$obj->email<br>
$obj->name<br>
$obj->car<br>
$obj->phone<br>
<p>
<hr>
";
}
}
?>
</body>
</html>
page.php
<?php
mysql_connect("localhost", "db", "pw");
mysql_select_db("db");
mysql_query("insert into all_emails (name, email, car, phone) values ('".$_POST['name']."','".$_POST['email']."','".$_POST['car']."', '".$_POST['phone']."' )");
?>
<html>
<head>
<meta http-equiv=refresh content="0; URL=./input.php">
</head>
</html>
Here is the if statement I am trying.
<?php
mysql_connect("localhost", "db", "pw");
mysql_select_db("db");
if( isset($_POST["cars_coffee"] ) ) {
$sql = "INSERT INTO cars_and_coffee (name, email, car, phone) values ('".$_POST['name']."','".$_POST['email']."','".$_POST['car']‌​."', '".$_POST['phone']."' )");
mysql_query($sql) or die(mysql_error());
}
echo "Record is inserted";
}
?>
Hi use the following code :
NOTE : I highly suggest you to use mysqli or PDO. mysql functions are deprecated and are obsolate.
Please sanitize or safe cast your data before inserting into your database.
Also NOTE: In form I am redirecting to the same form page. Please use the appropriate php file name or routing path.
db_connect.php
$host = 'localhost';
$user = 'root';
$password = 'root';
$database = 'skerp';
$connection_error = 'Sorry!!! We are experiencing problems with the database settings';
$link = mysqli_connect($host, $user, $password, $database) or DIE($connection_error);
The following is the implementation
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if($_SERVER['REQUEST_METHOD'] == 'POST'){
include_once ('db_connection.php');
if(in_array('cars_coffee', $_POST['chk'])){
$emails = mysqli_query($link, "INSERT INTO all_emails (name, email, car, phone) VALUES ('".$_POST['name']."','".$_POST['email']."','".$_POST['car']."', '".$_POST['phone']."' )");
}else{
//If it fails then put the condition here or you may skip else part
echo 'Not Exists';
}
echo '<pre>';
print_r($_POST);
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<input type="checkbox" name="chk[]" value="cars_coffee">Cars & Coffee<br>
<input type="checkbox" name="chk[]" value="kentucky">Kentucky Derby Party<br>
<input type="checkbox" name="chk[]" value="july">July 4th<br>
<input type="checkbox" name="chk[]" value="labor">Labor Day<br>
<input type="checkbox" name="chk[]" value="new_year">New Years Day<br>
<input type="checkbox" name="chk[]" value="all" onClick="toggle(this)">Select All<br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
Hope it helps. Happy Coding!
You can use the isset method to check if a checkbox was selected.
if ( isset ( $_POST ["cars_coffee"] ) )
{
// do something
}
if ( isset ( $_POST ["kentucky"] ) )
{
// do something else
}
...
There seems to be a slight problem with your logic because you are using checkboxes to retrieve data from the user. If you want the user to only select one checkbox, use a radio button. That will make them unable to select multiple. If I'm just not understanding you correctly and you really do want users to be able to select multiple boxes, then keep using checkboxes, but change the name attribute of each checkbox to be unique. Because right now, every checkbox has the same name, so it is going to read only the last checkbox that they checked.
The logic would go something like this if you continued using checkboxes and gave each checkbox a unique name:
$sql = '';
// make sure that the checkbox is set
if(isset($_POST['kentucky_checkbox'])){
{
$sql += 'INSERT INTO kentucky VALUES ...;';
}
if(isset($_POST['labor_checkbox'])){
{
$sql += 'INSERT INTO labor VALUES ...;';
}
etc.
...
// execute $sql
The logic would go something like this if you used radio buttons:
// make sure that the variable is set
if(isset($_POST['chk[]'])){
{
// check what the value is
switch ($_POST['chk[]']) {
case 'option1':
// set the table
$table = 'table1';
break;
case 'option2':
$table = 'table2';
break;
case 'option3':
$table = 'table3';
break;
}
}
...
$sql = 'INSERT INTO ' . $table . ' VALUES ...';

How to keep php $_GET value from a submit button after form submit from javascript?

I have a php page with 2 submit buttons and 2 radio buttons:
<?php
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
?>
<form method="get">
<button type='submit' name='choice' value='1'>Choice1</button>
<button type='submit' name='choice' value='2'>Choice2</button>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If I click on Slovenian radio button, I get:
http://localhost/index.php?language=Slovenian
If I then click on Choice2 submit button, "language" is saved and I get:
http://localhost/index.php?choice=2&language=Slovenian
If I then click on English radio button, "choice" is not saved and I get:
http://localhost/index.php?language=English
This is my first php page and after hours of googling i added this line:
<input type="hidden" name="choice" value="<?php echo $choiceIdx; ?>">
The "choice" is now saved, but i get:
http://localhost/index.php?choice=1&language=Slovenian&choice=2
I don't want it twice in url. Please explain what i am doing wrong. Thank you!
EDIT: I want to use GET (and not POST) because the URL has to be saved as a bookmark.
Here is an alternate version (as a followup to my first answer) that updates the hidden value when clicking the choice-button:
<script>
function setChoice(val) {
document.getElementById('hiddenChoice').value=val;
}
</script>
<form method="get">
<button type='submit' onClick="setChoice(1);">Choice1</button>
<button type='submit' onClick="setChoice(2);">Choice2</button>
<input type='hidden' id='hiddenChoice' name='choice' value='<?php echo $choiceIdx; ?>'>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If you have more values to retrieve you might want to create a more sofisticated and less specific js-function. You could easily pass in the id of the target input f.e.
Also you should rethink if it's realy neccessary to always submit the form, or if it might be better to first collect all the data and only send one form back to the server.
Add that to your form:
<input type='hidden' name='choiceStored' value='<?php echo $choiceIdx; ?>'>
This will store the last received val for choice and re-send it at the next form submit.
and change your php to:
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
// eighter get new value
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
// or if we don't have a new value, take the 'stored' one:
} elseif (isset($_GET['choiceStored']))
{
$choiceIdx = $_GET['choiceStored'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
You are passing the same name twice. 'choice' has been defined as both the hidden value name and the button value name. To be able to differentiate, you should change the hidden value name to something like 'savedchoice'. And reference it by that name

Count checked checkbox(array) numbers & saving checked checkboxes

I have an array of checkbox in a table in PHP file like this :
echo "<td $Blocked><input type =\"checkbox\" name=\"Blocked[]\" value=\"checkblock\" /></td>";
I am trying to get the value of number of checked checkboxes and save it to DB.
$Blocked = 'unchecked';
if ((isset($_POST['edit_tc']))) {
if (isset($_POST['Blocked'])) {
if (is_array($_POST['Blocked'])) {
foreach($_POST['Blocked'] as $value) {
error_log($value);
}
}
else {
$value = $_POST['Blocked'];
error_log($value);
}
$Blocked = 'checked';
}
}
"edit_tc" is the Submit button.
How do I take the number of it when the user checks the checkbox & clicks Submit button to save it to a table column?
I guess below code will solve all your problem.
<?php
$hello = array();
if(isset($_POST['submit'])) {
extract($_POST);
print_r($hello); //print all checked elements
}
?>
<form method="post">
<input type="checkbox" name="hello[]" value="1" <?php if(in_array(1, $hello)){ echo 'checked'; } ?>>
<input type="checkbox" name="hello[]" value="2" <?php if(in_array(2, $hello)){ echo 'checked'; } ?>>
<input type="checkbox" name="hello[]" value="3" <?php if(in_array(3, $hello)){ echo 'checked'; } ?>>
<input type="checkbox" name="hello[]" value="4" <?php if(in_array(4, $hello)){ echo 'checked'; } ?>>
<button type="submit" name="submit" value="Submit">Submit</button>
</form>
You have to check the value of each checkbox inside the checkbox array you are getting using in_arrayfunction of PHP.
If you need to understand whole thing, just let me know.
Will be glad to help you out.
Regards.
You can use this method...
if ((isset($_POST['edit_tc']))) {
if (isset($_POST['Blocked']))
{
$data = $_POST['Blocked'];
foreach ($data as $checkedValue)
{
$qry = mysql_query("INSERT INTO `Table_name` WHERE `column_id` = '$checkedValue'");
}
}
}
This is the method that will use to save each value as different records... You can modify that if needed.
You can simply use count() function to get total number of checkbox checked by user.
As only those checkbox values are posted to submitted page which are checked by user and if checkbox is not checked , its value will not be submitted. i.e The unchecked checkbox will not exist on submitted page.
USE:
$totalCheckboxChecked=count($_POST['Blocked']);

How to check if a radio button is clicked?

My code looks like this:
form action="familytree.php" method="post">
<?php
foreach ($spouses as $spouse) {
if (!empty($spouse['mname'])) {
$name = $spouse['fname'].' '.$spouse['lname'].' ('.$spouse['mname'].')';
}
else {
$name = $spouse['fname'].' '.$spouse['lname'];
}
if ($spouse['ended'] == '1') {
$married = '';
$divorced = 'checked';
}
else {
$married = 'checked';
$divorced = '';
}
?>
<div class="form_section dates">
<h3><?php echo $name; ?></h3>
<p>
<input type="radio" id="married_option" name="married_divorced_options" <?php echo $married; ?> value="1"/>
<label for="edate">Married</label>
<input type="radio" id="divorced_option" name="married_divorced_options" <?php echo $divorced; ?> value="1"/>
<label for="sdate">Divorced</label>
</p>
<div class="half" style="display: inline">
<input type="text" name="sdate_<?php echo $spouse['individual_id']?>" id="sdate_<?php echo $spouse['individual_id']?>" value="<?php echo $spouse['start_date']; ?>" placeholder="Rašykite sutuoktuvių datą čia"/>
<?php echo $this->formError->error("sdate_".$spouse['individual_id'].""); ?>
</div>
<div id="divorced" class="half" style="display:none">
<input type="text" name="edate_<?php echo $spouse['individual_id']?>" id="edate_<?php echo $spouse['individual_id']?>" value="<?php echo $spouse['end_date']; ?>" placeholder="Rašykite skyrybų datą čia"/>
<?php echo $this->formError->error("edate_".$spouse['individual_id'].""); ?>
</div>
</div>
<?php
}
?>
<p class="submit">
<input class="first-btn" type="submit" id="edit-relationship" name="edit-relationship" value="Edit"/>
</p>
</form>
jQuery("#divorced_option").click(function() {
document.getElementById("divorced").style.display = "inline-block";
});
jQuery("#married_option").click(function() {
document.getElementById("divorced").style.display = "none";
});
What I would like to know is how to check if a radio button is clicked when you don't know its full name, only half of it. For example, #divorced_option is not full name, it should be something like this #divorced_option_161, #divorced_option_161... So, the code should check if the radio button that has divorced_option in its name is clicked. Is there a way to achieve this?
EDIT
It works with jQuery("[id^='married_option']").click(function(){}). But I forgot to mention in my original question that the element divorced isn't full name as well, it should be divorced_161, divorced_162, depending of the name of the radio button that is clicked. How can I hide the element that matches with the radio button?
Use the attribute starts with selector (ex. [name^="value"]):
jQuery("[id^='divorced_option']").click(function() {
document.getElementById("divorced").style.display = "inline-block";
});
jQuery("[id^='married_option']").click(function() {
document.getElementById("divorced").style.display = "none";
});
Have a look at the jQuery selectors.
The 'Attribute Contains' selector would be useful here, which means your code would be :
jQuery("[id*='divorced_option']").click(function() {
document.getElementById("divorced").style.display = "inline-block";
});
jQuery("[id*='married_option']").click(function() {
document.getElementById("divorced").style.display = "none";
});
You can select the elements based on the #divorced_option_[number] pattern while checking if they are selected like this:
$("input[id*=divorced_option]:checked");
If you would like to check wether the divorced_option substring is in the name="" attribute of the radio element, then change the id from the selector to name, like so:
$("input[name*=divorced_option]:checked");
After this, just check wether or not jQuery returned an actual element.

Categories