checkbox handling php multiple checkbox - php

Working on a simple php code. When it press on only PH it show hello, and only on chlorine it show yello. When both is pressed it show sello.
<?php
if(isset($_POST['submit'])){
foreach($_POST['verdi'] as $animal){
if(isset($_POST['verdi[]==PH']))
{
echo "hello";
}
}
}
?>
<form name="input" action="" method="POST">
<input type="checkbox" name="verdi[]" value="PH">PH<br>
<input type="checkbox" name="verdi[]" value="Chlorine">Chlorine<br>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

You can do a simple check in PHP:
if( in_array("PH", $_POST["verdi"]) ){
echo "in array!";
}

if(isset($_POST['submit']) && is_array($_POST['verdi'])) {
$checked = array();
foreach($_POST['verdi'] as $animal) {
// you can do extra validation here.
$checked[] = $animal;
}
if(in_array("PH", $checked) && in_array("Chlorine", $checked)) {
echo "sello";
} else {
if(in_array("PH", $checked)) {
echo "hello";
} else if(in_array("Chlorine", $checked)) {
echo "yello";
}
}
}

Related

PHP actions with multiple Buttons resetting others

here you see my code example:
<?php
session_start();
$arbeit = $_GET["arbeit"];
echo "Angelegte Prüfung: ";
echo $arbeit;
$damen = 0;
$herren = 0;
if (array_key_exists('add_Fem',$_POST)) {
$damen = 1; // BESETZT DAMEN
}
elseif (array_key_exists('sub_Fem',$_POST)) {
$damen = 0; // Reset counter
}
elseif (array_key_exists('add_Mal',$_POST)) {
$herren = 1; // BESETZT HERREN
}
elseif(array_key_exists('sub_Mal',$_POST)) {
$herren = 0; // Reset counter
}
?>
<form method='post'>
<input name='add_Fem' type="submit" value='Damen' class="button">
</form>
<form method='post'>
<input name='sub_Fem' type="submit" value='Reset Damen' class="button">
<h3><em>
<?php
if ($damen == 1) {
echo "DAMEN BESETZT!";
} else {
echo "DAMEN FREI!";
}
?>
</em></h3>
</form>
<form method='post'>
<input name='add_Mal' type="submit" value='Herren' class="button">
</form>
<form method='post'>
<input name='sub_Mal' type="submit" value='Reset Herren' class="button">
<h3><em>
<?php
if ($herren == 1) {
echo "HERREN BESETZT!";
} else {
echo "HERREN FREI!";
}
?>
</em></h3>
</form>
the problem is, when i'm try to set both to 1(male and female) the other variable gets reset to 0. And i dont know why they are affect each other!
Also PHP isset not solves my problem, same situation, that was my first try.
I hope you can give me some advice.
Thank you

PHP required checkbox field

I have a form with multiple checkboxes. I want to allow the user to select at least 1 in each checkbox field, if the user does not check any of the options in the checkbox, a message will display "You have to select at least one." How do I do it? I have here some of my codes:
<div>
<div><span class="font-2">Categories:</span></div>
</div>
<div class = "addinfo">
<?php $categories = array('Breakfast', 'Lunch', 'Dinner', 'Snack', 'Grill', 'Buffet', 'Fast Food');
$values = explode(',' , $row['categories']);
?>
<?php foreach($categories as $category) {
$cat='';
foreach($values as $value){
if($value == $category){
$cat ="checked";
}
?>
<input <?php echo $cat ?> type="checkbox" name="category[]" value="<?php echo $category?>"><?php echo $category?><br>
<?php }
}?>
</div>
form
<form method = "POST" action = "<?php echo base_url().'/index.php/AdminController/operation'?>">
AdminController
public function addResto(){
$this->load->model('AdminModel');
$this->AdminModel->insert();
$this->getRestos();
}
public function operation(){
if(isset($_POST['btn'])){
if(empty($_POST['id'])){
$this->addResto();
}
else{
$this->updatingResto();
}
}
}
public function updateResto($id){
$this->load->model('AdminModel');
$restaurantinfo['restaurantinfo']=$this->AdminModel->getResto($id);
$this->load->view('admin/UpdateRestoPage',$restaurantinfo);
}
public function updatePage(){
$this->load->view('admin/UpdateRestoPage');
}
public function updatingResto(){
$id = $_POST['id'];
$this->load->model('AdminModel');
$this->AdminModel->update($id);
}
You should also check if there is a checkbox that is checked
public function operation(){
if(isset($_POST['btn'])){
if(empty($_POST['category'])){
$this->load->view('YOUR_VIEW_FILE',array('error'=>'category'));
}else if(empty($_POST['id'])){
$this->addResto();
}
else{
$this->updatingResto();
}
}
}
your view file add a condition
<?php
if(!empty($error) && $error=="category"){
?>
<script>alert("You have to select at least one.");</script>
<?php
}
?>
Add validation in your called php
<?php
$checked = false;
foreach($_POST["category"] as $key) {
if(!empty($key)) {
$checked = true;
}
}
if(!$checked) {
echo "<script>";
echo "alert('You have to select at least one.');";
echo "history.back();";
echo "</script>";
exit();
}
?>
in your controllers operation function use
if (isset($_POST['mycheckbox'])) {
echo "checked!";
} esle {
//send again with error message
}
Using this validation in javascript:
$("input:checkbox[name='a']:checked").length == 0
Example:
HTML code:
<from name='frm1' method='' action='POST'>
<label>Favorites:</label>
<span>sports</span><input type="checkbox" name="fav" value="1"/>
<span>music</span> <input type="checkbox" name="fav" value="2"/>
<span>reading</span> <input type="checkbox" name="fav" value="3"/>
<input type="button" value="validate">
</form>
Javascript code:
function validate() {
//replace with your own code here
if ($('input:checkbox[name="fav"]:checked').length == 0) {
alert("You have to select at least one.");
}
}
$("input[type='button']").click(validate)
It's just a simple example to demonstrate the use of :check selector(JQuery), you need to
change and embed it in your project!
try to add this in your html code:
<script type="text/javascript">
function check () {
var inputs = document.querySelectorAll("input[type='checkbox']");
for(var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
return true;
}
}
alert("You have to select at least one.");
return false;
}
</script>
This one will show the error before the page refreshes. And add something like this in your html :
<input type = "button" onclick = "check();">
UPDATE : try to replace your code with this.
<div>
<div><span class="font-2">Categories:</span></div>
</div>
<script type="text/javascript">
function check () {
var inputs = document.querySelectorAll("input[type='checkbox']");
for(var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
return true;
}
}
alert("You have to select at least one.");
return false;
}
</script>
<div class = "addinfo">
<?php $categories = array('Breakfast', 'Lunch', 'Dinner', 'Snack', 'Grill', 'Buffet', 'Fast Food');
$values = explode(',' , $row['categories']);
?>
<?php foreach($categories as $category) {
$cat='';
foreach($values as $value){
if($value == $category){
$cat ="checked";
}
?>
<input <?php echo $cat ?> type="checkbox" name="category[]" value="<?php echo $category?>"><?php echo $category?><br>
<?php }
}?>
<input type = "button" onclick = "check();">
</div>

Best Solution for this array

I am using checkboxes to query the database and I am struggling with this one, I am new to MySQL and PHP so sorry if this is simple!
Here is my code that I have...
<input type="checkbox" name="season2005" value="2005" <?php if(isset($_POST['season2005'])) echo "checked='checked'"; ?> > 2005-06
<input type="checkbox" name="season2006" value="2006" <?php if(isset($_POST['season2006'])) echo "checked='checked'"; ?> > 2006-07
<input type="checkbox" name="season2007" value="2007" <?php if(isset($_POST['season2007'])) echo "checked='checked'"; ?> > 2007-08
<input type="checkbox" name="season2008" value="2008" <?php if(isset($_POST['season2008'])) echo "checked='checked'"; ?> > 2008-09
<input type="checkbox" name="season2009" value="2009" <?php if(isset($_POST['season2009'])) echo "checked='checked'"; ?> > 2009-10
<input type="checkbox" name="season2010" value="2010" <?php if(isset($_POST['season2010'])) echo "checked='checked'"; ?> > 2010-11
<input type="checkbox" name="season2011" value="2011" <?php if(isset($_POST['season2011'])) echo "checked='checked'"; ?> > 2011-12
<input type="checkbox" name="season2012" value="2012" <?php if(isset($_POST['season2012'])) echo "checked='checked'"; ?> > 2012-13
<input type="checkbox" name="season2013" value="2013" <?php if(isset($_POST['season2013'])) echo "checked='checked'"; ?> > 2013-14
if (#$_POST['season2005'] == ""){ $season2005 = "0000"; } else { $season2005 = "2005"; }
if (#$_POST['season2006'] == ""){ $season2006 = "0000"; } else { $season2006 = "2006"; }
if (#$_POST['season2007'] == ""){ $season2007 = "0000"; } else { $season2007 = "2007"; }
if (#$_POST['season2008'] == ""){ $season2008 = "0000"; } else { $season2008 = "2008"; }
if (#$_POST['season2009'] == ""){ $season2009 = "0000"; } else { $season2009 = "2009"; }
if (#$_POST['season2010'] == ""){ $season2010 = "0000"; } else { $season2010 = "2010"; }
if (#$_POST['season2011'] == ""){ $season2011 = "0000"; } else { $season2011 = "2011"; }
if (#$_POST['season2012'] == ""){ $season2012 = "0000"; } else { $season2012 = "2012"; }
if (#$_POST['season2013'] == ""){ $season2013 = "0000"; } else { $season2013 = "2013"; }
$seasons = array($season2005,$season2006,$season2007,$season2008,$season2009,$season2010,$season2011,$season2012,$season2013);
$seasonpick = implode(",",$seasons);;
$matcharrays = array("AND season in ($seasonpick)");
At the moment all of the data is being queried to the database, so if nothing is selected them then part of query from this is "AND season in (0000,0000,0000,0000) etc
How would I go about only getting those selected into the array and if none are selected then the array would be blank.
Hope you understand what I mean!
Here is a working form with some checkboxes that will allow you to test and get the sql you intended.
<?php
$dateArr=array();
if(isset($_POST['season']))
{
$dateArr=array_unique($_POST['season']);
$dateSearch=implode(",", $dateArr);
$sql=".... and season in (".$dateSearch.")";
echo $sql;
}
?>
<html>
<form action="?" method="post">
<?php
for($i=0;$i<10;$i++)
{
echo "<input type=\"checkbox\" name=\"season[]\" value=\"".($i+2005)."\"> ".($i+2005);
}
?>
<input type="submit">
</form>
Output when 2009, 2010 and 2011 selected:
.... and season in (2009,2010,2011)
Okay, so how it works:
Checkboxes are best used when they all have the same name ending in a []. This makes it a nice array on it's own.
If post data is set, we then quickly throw an array unique over it (good habit for the most part in these types of queries) so that there are no duplicate values.
Then simply implode it into a string and pop it into the SQL query.
Edit: Added functionality to re-check checkboxes when submitted.
<?php
$dateArr=array();
if(isset($_POST['season']))
{
$dateArr=array_unique($_POST['season']);
$dateSearch=implode(",", $dateArr);
$sql=".... and season in (".$dateSearch.")";
echo $sql;
}
?>
<html>
<form action="?" method="post">
<?php
for($i=0;$i<10;$i++)
{
$chk="";
if(!empty($_POST['season']))
{
if(in_array($i+2005, $_POST['season']))
{
$chk=" checked=\"checked\" ";
}
}
echo "<input type=\"checkbox\" name=\"season[]\" ".$chk." value=\"".($i+2005)."\"> ".($i+2005);
}
?>
<input type="submit">
</form>
Edit 2: Just add quotes in the right places :)
<?php
$dateArr=array();
if(isset($_POST['season']))
{
$dateArr=array_unique($_POST['season']);
$dateSearch=implode("', '", $dateArr);
$sql=".... and season in ('".$dateSearch."')";
echo $sql;
}
?>
<html>
<form action="?" method="post">
<?php
for($i=0;$i<10;$i++)
{
$chk="";
if(!empty($_POST['season']))
{
if(in_array(($i+2005)."i", $_POST['season']))
{
$chk=" checked=\"checked\" ";
}
}
echo "<input type=\"checkbox\" name=\"season[]\" ".$chk." value=\"".(($i+2005)."i")."\"> ".($i+2005)."i";
}
?>
<input type="submit">
</form>
Edit 3: I feel like this is starting to really answer much more than one question :)
You can simply check the textbox to make sure it isn't empty and then append to a SQL string:
$sql="";
if(!empty($_POST['text1']))
{
$sql.=" and ftgf>= ".$_POST['text1']." ";
}
Having said that, I would strongly suggest that you NEVER allow the user to enter in parts of the actual SQL you will run - unless it is a closed/secure environment, which means NOT an ope website.
Insert the below code
$seasons = array($season2005,$season2006,$season2007,$season2008,$season2009,$season2010,$season2011,$season2012,$season2013);
//start
$seasons2 = array();
foreach ($seasons as $season)
{
if($season!=="0000")
{
array_push($seasons2,$season);
}
}
$seasonpick = implode(",",$seasons2);
//end

PHP Multiple form in same page

I'm doing form in php but I have some problem.
First I will have 3 different form in the same page.
What I want is only 1 form appear and then with the answer a second form will appear and so on.
The answer of the form will be display on the same page.
For now my first form work and after get the answer go to the 2nd form but I want to submit the 2nd form the problem appear.
It delete the answer of my first form and don't do anything (everything start like I am in my first form).
I try to find the problem but can't have idea about how to solve it.
Here is my code:
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Q1?
<input type="number" name="nbtemplate" min="1" max="30">
<input type="submit" name="submitbutton1" value="Confirm!">
</form>
<?php
if(!isset($submitbutton1)) {
if (!empty($_POST['nbtemplate']) != "") {
echo "<b>{$_POST['nbtemplate']}</b> !\n";
echo "<br />";
$Nnbtemplate = $_POST['nbtemplate'];
$result = mysql_query("UPDATE tb SET day='$Nnbtemplate'") or die(mysql_error());
?>
<form action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
Q2? <br>
<?php
for ($i = 1; $i <= $Nnbtemplate; $i++) { // start loop
echo "Template ";
echo $i;
?>
<input type="number" name="nbtime" min="1" max="96">
<?php
}
echo '<input type="submit" name="submitbutton2" value="Confirm!">';
echo '</form>';
if(isset($submitbutton1) && !isset($submitbutton2)) {
if (!empty($_POST['nbtime']) != "") {
echo "<b>{$_POST['nbtime']}</b> !\n";
echo "<br />";
$nbtime = $_POST['nbtime'];
for ($j = 1; $j <= $nbtime; $j++) {
echo "Time";
echo $j;
?>
Q3:
<input type="time" name="starttime"> To <input type="time" name="endtime">
<?php
}
echo '<input type="submit">';
echo '</form>';
}
}
}
}
?>
That is some gnarly code you got there, brother. This is a really simple task when handled with some javascript. Then you can have a single post to your php. I like using the jQuery framework so here's a couple links I found quickly: this one and this one
Example code in response to comment about building form elements dynamically:
<html>
<head>
<!-- load jquery library -->
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<form action="toyourpage.php">
How Many?:
<input type="text" name="number" id="number">
<div id="add"></div>
</form>
<!-- javascript go -->
<script type="text/javascript">
$(document).ready(function()
{
$('input#number').keyup(function()
{
var num = $(this).val(); // get num
if(!isNaN(num)) // check if number
{
$('div#add').html(''); // empty
for(i = 1; i <= num; i++) // add
{
$('div#add').append('New Field ' + i + ': <input type="text" name="next_' + i + '" id="next' + i + '"><br>');
}
}
else
{
alert('Valid number required');
}
});
});
</script>
</body>
</html>
I did some changes on Your code, and have tested, it works.
You had any mistakes in your {} brackets and if conditions. Also as I commented I added extract($_POST).
<?php
extract ( $_POST );
if (! isset ( $submitbutton1 ) && !isset($submitbutton2)) {
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Q1? <input type="number" name="nbtemplate" min="1" max="30"> <input
type="submit" name="submitbutton1" value="Confirm!">
</form>
<?php ;
}
if (isset ( $submitbutton1 )) {
if (! empty ( $_POST ['nbtemplate'] ) != "") {
echo "<b>{$_POST['nbtemplate']}</b> !\n";
echo "<br />";
$Nnbtemplate = $_POST ['nbtemplate'];
$result = mysql_query("UPDATE tb SET day='$Nnbtemplate'") or
die(mysql_error());
?>
<form action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
Q2? <br>
<?php
for($i = 1; $i <= $Nnbtemplate; $i ++) { // start loop
echo "Template ";
echo $i;
?>
<input type="number" name="nbtime" min="1" max="96">
<?php
}
echo '<input type="submit" name="submitbutton2" value="Confirm!">';
echo '</form>';
}
}
if ( isset ( $submitbutton2 )) {
if (! empty ( $_POST ['nbtime'] ) != "") {
echo "<b>{$_POST['nbtime']}</b> !\n";
echo "<br />";
$nbtime = $_POST ['nbtime'];
for($j = 1; $j <= $nbtime; $j ++) {
echo "Time";
echo $j;
?>
Q3:
<input type="time" name="starttime"> To <input type="time"
name="endtime">
<?php
}
echo '<input type="submit">';
echo '</form>';
}
}
?>

How can I check if atleast 2 checkboxes are checked in php?

I need to have php validation that says at least 2 checkboxes should be checked...
I have been trying different things but unable to get the right results.
<?php
if(!empty($_POST['opt'])) {
foreach($_POST['opt'] as $check) {
echo $check;
}
$checkboxes = count($check);
echo '$checkboxes';
}
?>
<form action="index.php" method="post">
<input type="checkbox" name="opt[]" value="option1" />option1<br />
<input type="checkbox" name="opt[]" value="option2" />option2<br />
<input type="checkbox" name="opt[]" value="option3" />option3<br />
<br /><br />
<input type="submit" name="formSubmit" value="Send" />
</form>
if(count($_POST['opt']) >= 2)
{
// at least 2 are checked
}
My example uses the opposite logic to the first person.
count_check = count($_POST['opt'])
if(count_check < 2)
{
//stop submission
}
else
{
//Proceed
}
You can try this:
<?php
if( is_array($_POST['opt']) )
{
foreach($_POST['opt'] as $check)
echo $check;
if(count($_POST['opt']) >= 2)
{
echo 'Valid';
}
else
{
echo 'Not valid';
}
}
else
echo 'Nothing checked';
?>

Categories