Php multiple isset. Any other way to make this work - php

I'm making a form where i have to insert in my dB several values from a checkbox btn group into different columns. I also have to insert two different values depending if the btn is checked or not.
I made it work in the following way, but is there another way for this became more simple? It´s a lot of issets :).
Thanks for your time.
Best regards!
NM
<?php
if(isset($_POST["submit"])){
// Create connection
include ('connection.php');
if(isset($_POST['fixvalue']) && ($_POST['fixvalue'] == 0)) {
$fixvalue= "fixvalue";
} else {
$fixvalue= 0;
};
if(isset($_POST['frtvalue']) && ($_POST['frtvalue'] == 0)) {
$valueone= "valueone";
} else {
$valueone= 0;
};
if(isset($_POST['secvalue']) && ($_POST['secvalue'] == 0)) {
$valuetwo= "valuetwo";
} else {
$valuetwo= 0;
};
if(isset($_POST['thevalue']) && ($_POST['thevalue'] == 0)) {
$valuethree= "valuethree";
} else {
$valuethree= 0;
};
if(isset($_POST['fovalue']) && ($_POST['fovalue'] == 0)) {
$valuefour= "valuefour";
} else {
$valuefour= 0;
};
if(isset($_POST['fitvalue']) && ($_POST['fitvalue'] == 0)) {
$valuefive= "valuefive";
} else {
$valuefive= 0;
};
$sql = "INSERT INTO values(fixvalue,valueone,valuetwo,
valuethree,valuefour,valuefive)
VALUES('".$fixvalue."','".$valueone."','".$valuetwo."',
'".$valuethree."','".$valuefour."','".$valuefive."')";
if ($con->query($sql) === TRUE) {
echo'<button class="btn btn-success" style="left:400px;bottom:20px;width:200px;">Sucess</button>';
echo "<script type= 'text/javascript'>alert('New record OK');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" $con->error."');</script>";
}
$con->close();
}
?>

Here's what I would do:
<form action="" method="post">
<input type="checkbox" name="fixvalue"> Checkbox<br>
<input type="checkbox" name="valueone"> Checkbox 1<br>
<input type="checkbox" name="valuetwo"> Checkbox 2<br>
<input type="checkbox" name="valuethree"> Checkbox 3<br>
<input type="checkbox" name="valuefour"> Checkbox 4<br>
<input type="checkbox" name="valuefive"> Checkbox 5<br>
<input type="submit" name="submit">
</form>
<?php
$fields = [
'fixvalue' => 0,
'valueone' => 0,
'valuetwo' => 0,
'valuethree' => 0,
'valuefour' => 0,
'valuefive' => 0
];
if($_POST['submit']){
foreach($_POST as $key => $value) {
if($key !== 'submit') {
$fields[$key] = $key;
}
}
extract($fields);
$sql = $db->prepare("INSERT INTO table_name (fixvalue, valueone, valuetwo, valuethree, valuefour, valuefive) VALUES(:fixvalue, :valueone, :valuetwo, :valuethree, :valuefour, :valuefive)");
foreach ($fields as $key => $value) {
$sql->bindValue(':'.$key, $$value);
}
$sql->execute();
}
?>

$checks = array(
'fixvalue',
'frtvalue',
'secvalue',
'thevalue',
'fovalue',
'fitvalue'
);
$data = array();
foreach( $checks as $value){
$data[$value] = isset($_POST[$value]) && $_POST[$value] != '' ? $_POST[$value] : 0;
}
Than use $data['frtvalue'] etc in a prepared sql statement

Related

Validate checkboxes values in PHP

I have a group of checkboxes with different values each. I want to assign their values in php variables which i'm going to send to database. The main problem is that i don't know how to check inside the php code if the values of selected items matching their default values which i setup in the html (apple == apple, samsung == samsung) and so on. This is because someone can just change the input value inside the console and insert whatever he likes in my DB. Any ideas how i can sort this out. Many thanks!
<form action="" method="POST">
<label for="apple">Apple</label>
<input id="apple" type="checkbox" name="myCheckBoxes[]" value="Apple">
<label for="samsung">Samsung</label>
<input id="samsung" type="checkbox" name="myCheckBoxes[]" value="Samsung">
<label for="lenovo">Lenovo</label>
<input id="lenovo" type="checkbox" name="myCheckBoxes[]" value="Lenovo">
<label for="google">Google Pixel</label>
<input id="google" type="checkbox" name="myCheckBoxes[]" value="Google Pixel">
<button type="submit" name="submit">Send</button>
</form>
PHP Code:
if (isset($_POST['submit'])) {
$checkBoxes = $_POST['myCheckBoxes'];
$numberSelected = count($checkBoxes);
if ($numberSelected > 3) {
echo 'Please select only 3 from the options';
} else {
for ($i = 0; $i < $numberSelected; $i++) {
$option1 = $checkBoxes[0];
$option2 = $checkBoxes[1];
$option3 = $checkBoxes[2];
}
echo 'You have selected', ' ', $option1, ' ', $option2, ' ', $option3;
}
}
You can define a constant array with the allowed values, then only use values from that array when they correspond to the input value.
const ALLOWED_VALUES = [
"apple" => "Apple",
"samsung" => "Samsung",
"lenovo" => "Lenovo",
"google pixel" => "Google Pixel",
];
if (isset($_POST['submit'])) {
$checkBoxes = $_POST['myCheckBoxes'];
$options = [];
if (count($checkBoxes) > 3) {
echo 'Please select only 3 from the options';
} else {
foreach($checkBoxes as $box) {
$box = strtolower(trim($box));
if(array_key_exists($box, ALLOWED_VALUES)){
$options[] = ALLOWED_VALUES[$box];
}
}
$option1 = (array_key_exists(0, $options))? $options[0]: null;
$option2 = (array_key_exists(1, $options))? $options[1]: null;
$option3 = (array_key_exists(2, $options))? $options[2]: null;
echo 'You have selected', ' ', $option1, ' ', $option2, ' ', $option3;
}
}
The code above will accept "APPLE" but will use "Apple" anything not found or empty will be set to null. Run it live here: https://onlinephp.io/c/8409e
you can do it through the help of or (||) , and (&&) operator in else part of if condition.
if(($option1=='Apple' || $option1=='Samsung' || $option1=='Lenovo'||$option1=='Google Pixel') && ($option2=='Apple' || $option2=='Samsung' || $option2=='Lenovo'||$option2=='Google Pixel') && ($option3=='Apple' || $option3=='Samsung' || $option3=='Lenovo'||$option3=='Google Pixel')){
echo 'You have selected', ' ', $option1, ' ', $option2, ' ', $option3;
}else{
echo"Please select suggested checkbox";
}

multiple checkbox and price calculation using php

i have table service in database db.
it has 3 fields
id,
service_type,
amount.
i have html form which has checkbox to select service type,i got service type selected but amount must be calculated auto and store in database amount column. but one error when i select service from checkbox it is selected and store in database but price is not stored.
my script is as follow:
<input type="checkbox" name="services[]" value="oilchange"
<input type="checkbox" name="services[]" value="acrepair"
<input type="checkbox" name="services[]" value="tyrechange"
<input type="submit" name="btnservice" value="Confirm Services">
now php script is as follow:
<?php $price=0.0;if (isset($_POST['services'])) {
$service=$_POST['services'];
$c=count($service);
for ($i=0; $i < $c; $i++) {
if ($service[$i]==fullservice) {
$price=$price+5000;
$iq="INSERT INTO tblservices( amount) VALUES ('$price')";
$run=mysqli_query($con,$iq);
if ($run) {
}
}
elseif ($service[$i]==tyrebalance) {
# code...
$price=$price+4000;
$iq="INSERT INTO tblservices( amount) VALUES ('$price')";
$run=mysqli_query($con,$iq);
if ($run) {
}
}
elseif($service[$i]==oilchange) {
# code...
$price=$price+3000;
$iq="INSERT INTO tblservices( amount) VALUES ('$price')";
$run=mysqli_query($con,$iq);
if ($run) {
}
}
elseif ($service[$i]==acrepair) {
# code...
$price=$price+2000;
$iq="INSERT INTO tblservices( amount) VALUES ('$price')";
$run=mysqli_query($con,$iq);
if ($run) {
}
}
elseif ($service[$i]==tyrechange) {
# code...
$price=$price+1000;
$iq="INSERT INTO tblservices( amount) VALUES ('$price')";
$run=mysqli_query($con,$iq);
if ($run) {
}
}
}
}if (isset($_POST['btnservice'])) {
$a=$_POST['services'];
$type=implode("/",$a);
$query="insert into tblservices(service_type,amount) values('$type','$price')";
$run=mysqli_query($con,$query);
if ($run) {
echo "<script type = \"text/javascript\">
alert(\"Services Selected.................\");
window.location = (\"services.php\")
</script>";
}
else{
echo "<script type = \"text/javascript\">
alert(\"Login Failed. Try Again................\");
window.location = (\"services.php\")
</script>";
}
}?>
i'm new guys sorry that's why i cann't upload images i need to earn reputations so i could able to post images for better or detailed explanation of my question.
i could see two type of queries in your sample.
Sharing here single service types insertion and insertion with total price. Hope this helps!!
<div class="container">
<form action="" method="post">
<input type="checkbox" name="services[]" value="oilchange" />oilchange
<input type="checkbox" name="services[]" value="acrepair" />acrepair
<input type="checkbox" name="services[]" value="tyrechange" />tyrechange
<br/>
<input type="submit" name="btnservice" value="Confirm Services">
</form> <?php
$serviceChargeArr = array(
'fullservice' => 5000,
'tyrebalance' => 4000,
'oilchange' => 3000,
'acrepair' => 2000,
'tyrechange' => 1000
);
$priceTotal = 0.0;
if (isset($_POST['btnservice'])) {
if (isset($_POST['services'])) {
$serviceArr = $_POST['services'];
$serviceArrCnt = count($serviceArr);
//QUERY 1 - insert each with respect to clicked checkboxes
for ($i = 0; $i < $serviceArrCnt; $i++) {
if ($eachPrice = $serviceChargeArr[$serviceArr[$i]]) {
$insertArr[] = "('$serviceArr[$i]', '$eachPrice')";
}
}
if (!empty($insertArr)) {//sigle insert query -each service and its price will be inserted
$query="insert into tblservices (service_type, amount)
values".implode(", ",$insertArr ).";";
echo $query."<br/>";
}//QUERY 1 ENDS
//QUERY 2 - insert single row with comma separated values and total price
for ($i = 0; $i < $serviceArrCnt; $i++) {
if ($eachPrice = $serviceChargeArr[$serviceArr[$i]]) {
$priceTotal += $eachPrice;
}
}
if (!empty($serviceArr)) {
$seviceList = implode(',', $serviceArr);
$query="insert into tblservices (service_type, amount)
values ('{$seviceList}' , '{$priceTotal}') ;";
echo $query."<br/>";
}//QUERY 2 ENDS
if($query) {
$run = mysqli_query($con, $query);
if ($run) {
echo "<br/> SUCCESS : inserted";
} else {
echo "<br/> ERROR : try again<br/>Mysql Error: ".$con->error;
}
}
}
} ?>
</div>

Search filters not functioning on first attempt

I have a search filter based on flags of different colors.
If I will search based on color it is showing result but when I will select white color flag it is showing entire data in my database table. But If I choose any other color apart from white color for the first time it will show result. And if I choose white color flag second time,then it gives the correct result. What might be the reason. I need help
//filter on flag_color
if($this->input->get('flg')){
$arr_flag = explode('-', $this->input->get('flg'));
$str_flag = implode(',',$arr_flag);
if(6 == $str_flag){
$str_flag = 0;
}
$str_condition .= 'AND t.sender_flag_color_id IN('.$str_flag.')';
}
array(
'0'=>array(
'color'=>'White',
'path'=>'whiteflag.png'),
'1'=> array(
'color'=>'Blue',
'path'=>'blueflag.png'),
'2'=>array(
'color'=>'Green',
'path'=>'greenflag.png'),
'3'=>array(
'color'=>'Yellow',
'path'=>'yellowflag.png'),
'4'=>array(
'color'=>'Red',
'path'=>'redflag.png') ,
'5'=>array(
'color'=>'Orange',
'path'=>'orangeflag.png')
);
view
<?php
$arr_params = $this->uri->uri_to_assoc();
$arr_flag = array();
if(isset($arr_params['flg']))
{ ?>
<input type="hidden" id="flag_in_url" name="flag_in_url" value="yes" />
<?php
}
?>
<!-- id="webmenu1" -->
<select class="flag_color" onchange="urgency_select('flag_color')" name="header_flag" id="webmenuflag1">
<?php
$arr_params = $this->uri->uri_to_assoc();
$arr_flag = array();
$int_flag_url = '';
if(isset($arr_params['flg']))
{
$int_flag_url = $arr_params['flg'];
}
if(isset($arr_flag_color))
{
foreach($arr_flag_color as $key=>$flag_color)
{
if($int_flag_url == $key)
{
$flag_selected = 'selected';
}
else
{
$flag_selected = '';
}
?>
<option <?php echo $flag_selected;?> value="<?php echo $key;?>" data-image="<?php echo base_url();?>images/<?php echo $flag_color['path'];?>"></option>
<?php
}
}
?>
js: urgency_select
var flag_color_id = '';
if(select_option == 'flag_color' || $( "#flag_in_url" ).val() == 'yes')
{
if($( ".flag_color" ).val() != undefined)
{
var flag_color_id = $( ".flag_color" ).val();
if(flag_color_id == 0)
flag_color_id = 6;
search_url += 'flg/'+flag_color_id+'/';
}
}
Its because conflict with the value of white color flag...
In the view I changed the code
if($int_flag_url == $key)
{
$flag_selected = 'selected';
}
to
if($int_flag_url == 0 || $int_flag_url == $key)
{
$flag_selected = 'selected';
}

PHP radio button group variables

I've simplified it for this question. But all I need to do is show a different result if a combination of buttons is checked. At the moment if Rice and Tea are checked there are no results.
<?PHP
if (isset($_POST['Submit1'])) {
$selected_radio = $_POST['food']."|".$_POST['drink'];
if ($selected_radio == 'rice' && 'tea') {
print '<h1>Rice and tea</h1>';
}
else if ($selected_radio == 'beans' && 'coffee') {
print '<h1>Beans and coffee</h1>';
}
}
?>
<form name ="form1" method ="POST" action =" ">
<p><input type = 'Radio' Name ='food' value= 'rice'>Rice</p>
<p><input type = 'Radio' Name ='food' value= 'beans'>Beans</p>
<p><input type = 'Radio' Name ='drink' value= 'tea'>Tea</p>
<p><input type = 'Radio' Name ='drink' value= 'coffee'>Coffee</p>
<input type = "Submit" Name = "Submit1" value = "Select">
</form>
(Apologies for asking a similar question earlier)
Update if condition
if (isset($_POST['Submit1'])) {
$selected_radio = $_POST['food']."|".$_POST['drink'];
if ($selected_radio == 'rice|tea') {
print '<h1>Rice and tea</h1>';
}
else if ($selected_radio == 'beans|coffee') {
print '<h1>Beans and coffee</h1>';
}
}
Change the condition of your if:
if (strpos($selected_radio, 'rice') !== FALSE && strpos($selected_radio, 'tea') !== FALSE) {
print '<h1>Rice and tea</h1>';
}
else if (strpos($selected_radio, 'beans') !== FALSE && strpos($selected_radio, 'coffee') !== FALSE) {
print '<h1>Beans and coffee</h1>';
}
(It's just a suggestion and I don't tested it ;))
Use this code:
$selected_radio_list = [
'rice|tea' => 'foo',
'beans|coffee' =>'bar'
];
$post = $_POST['food']. "|" .$_POST['drink'];
if(in_array($post, $selected_radio_list )){
echo $selected_radio_list[$post];
}

make sure atleast one checkbox is selected php

I have a little mailing form with a few checkboxes. At least one of the boxes need to be selected before mailing should start.
My HTML:
<input type='checkbox' id='part1' name='box1' value='box1' checked>
<label for="part1">Voor Leden agenda</label>
<br/>
<input type='checkbox' id='part2' name='box2' value='box2' checked>
<label for="part2">Voor Leiding agenda</label>
<br/>
<input type='checkbox' id='part3' name='box3' value='box3' checked>
<label for="part3">Verhuur agenda</label>
<br/>
<button type='submit' name='send'/>send</button>
My PHP:
if (isset($_POST['box1'])) {
$box1 = 'yes';
} else {
$box1 = 'No';
}
if (isset($_POST['box2'])) {
$box2 = 'yes';
} else {
$box2 = 'No';
}
if (isset($_POST['box3'])) {
$box3 = 'yes';
} else {
$box3 = 'No';
}
i would like to have a script that gives a message like below if no checkbox is selected:
if()
{
echo "<p class='redfont'>no checkboxes are selected</p>";
echo "<p><a href='javascript:history.back();'>Click to go back</a></p>";
}
edit: how can I give this message with php, only if all boxes are unchecked
if(!isset($_POST['box1']) && !isset($_POST['box2']) && !isset($_POST['box3']))
{
// none is set
}
You could even apply De Morgan's law and write this equivalent expression
if(isset($_POST['box1']) || isset($_POST['box2']) || isset($_POST['box3']))
{
// at least one of them is set
}
You could even send those 3 parameters to 1 isset call but then that would check if all of them are set, which is not your requirement.
Try this:
if(isset($_POST["box1"]) || isset($_POST["box2"]) || isset($_POST["box3"])) {
if(isset($_POST['box1'])) {
$box1 = 'yes';
} else {
$box1 = 'No';
}
if(isset($_POST['box2'])) {
$box2 = 'yes';
} else {
$box2 = 'No';
}
if(isset($_POST['box3'])) {
$box3 = 'yes';
} else {
$box3 = 'No';
}
} else {
echo "<p class='redfont'>no checkboxes are selected</p>";
echo "<p><a href='javascript:history.back();'>Click to go back</a></p>";
}
This one is more readable I think:
$boxes = ['box1', 'box2', 'box3'];
$checked = [];
foreach($boxes as $box){
if(isset($_POST[$box])){
$checked[] = $box;
}
}
if(count($checked) == 0){
// no boxes checked
echo "<p class='redfont'>no checkboxes are selected</p>";
echo "<p><a href='javascript:history.back();'>Click to go back</a></p>";
}else{
// at least one box is checked, you can do another foreach statement
with the $checked variable to do stuff with the checked ones
}
To do this for ANY number of checkboxes (Webistes are bound to expand), I assume all of you checkboxes are of the form box**i** :
if( strpos( implode(',' , array_keys($test)) , 'box' ) !== FALSE )
I use this function in JQuery:
jQuery.validation = function(){
var verif = 0;
$(':checkbox[id=list_exp]').each(function() {
if(this.checked == true){
verif++
}
});
if(verif == 0){
alert("no checkboxes are selected");
return false;
}
}

Categories