Validate checkboxes values in PHP - 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";
}

Related

Php multiple isset. Any other way to make this work

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

Php - How to return the result of foreach input?

I have one form for multiple input entries.
I would like loop through it to grab the data using the foreach function and return the result.
But somehow it keep failing because $_POST
<?php
$age = array(
"Peter"=> '35f',
"Ben"=> '37f',
"Joe"=> '43f'
);
foreach( $age as $x => $x_value ) {
(isset($_POST['$x_value'])) ? $y = $_POST['$x_value'] : '';
echo "Key=" . $x . ", Value=" . $x_value . ", Input=" . $y;
echo "\r\n";
}
?>
The form
<form action="" method="post">
<input name="35f" value="6d583"/>
<input name="37f" value="2ds43"/>
<input name="43f" value="5533d"/>
<input name="submit" value="submit"/>
</form>
Expected result :
Key=Peter, Value=35f, Input=6d583
Key=Ben, Value=37f, Input=2ds43
Key=Joe, Value=43f, Input=5533d
You dont need single quotes here:
$y = isset($_POST[$x_value]) ? $_POST[$x_value] : '';
You have to use $_value inside brackets without '' because it's a variable not an string
<?php (isset($_POST[$x_value])) ? $y = $_POST[$x_value] : '';

Is there a way of updating a large form with checkboxes effectively?

Having an issue updating a large form with checkboxes effectively to database.
Just for illustration:
<form action="save.php" method="post">
<?php
for {$i=0;$i<1000;$i++) {
echo '<input type="checkbox" name="product-' . $i . '">';
}
<input type="submit">
</form>
<?php
$posted_values = $_POST;
foreach($posted_values as $key=>$p) {
$chkbox = $posted_values[$p];
$update = 0;
if ($chkbox == 'on') {
$update = 1;
}
//Do some "expensive" checking for each posted value
$save_dbarray[$key] = $update;
}
//Do the actual updating to databased based on array `save_dbarray`
Is there any way of just adding changed checkboxes to the save_dbarray? (Only checked boxes would be posted to $_POST, but I want unchecked values to be a part of the update as well if they have changed) I have to do some expensive checking for each posted value, therefore
UPDATE
I dont want to have loop through all 1000 checkboxes. I just want to loop through the changed (from checked to unchecked or from unchecked to checked) checkboxes, but in above case $posted_values would only return checkboxes that has checked values (from unchecked to checked)
<?php
//I DONT want to have to do like this:
for {$i=0;$i<1000;$i++) {
$prodnr = 'product-' . $i;
$chkbox = $_POST[$prodnr];
$update = 0;
if ($chkbox == 'on') {
$update = 1;
}
//Do some "expensive" checking for every value
$save_dbarray[$key] = $update;
}
//Do the actual updating to databased based on array `save_dbarray`
You can use HTML array inputs and PHP to do the same.
A sample code will be like below.
<form action="save.php" method="post">
<?php
for ($i=0;$i<1000;$i++) {
echo '<input type="checkbox" name="products[]" value="' . $i . '"> '. $i .'<br>';
}
?>
<input type="submit">
</form>
<?php
print_r($_POST['products']); // Will contain your desired output
foreach($_POST['products'] as $i) {
$save_dbarray[$i] = 'on'; // 'on' or whatever value if you need.
// Actually you just need $_POST['products'], no need for this loop.
}
print_r($save_dbarray);
?>
EDIT
You need to loop through $_POST['products'] to find the new checked ones and you need to loop through $already_selected to find the unchecked ones.
<?php
// Select from db or something
$already_selected = array(2,3);
foreach($_POST['products'] as $i) {
if(!in_array($i,$already_selected)){
$save_dbarray[$i] = 'checked_update';
}
}
foreach($already_selected as $j) {
if(!in_array($j,$_POST['products'])){
$save_dbarray[$j] = 'unchecked_update';
}
}
print_r($save_dbarray);
// Do db update and select again and update $already_selected to display the checked ones
?>
<form action="save.php" method="post">
<?php
for ($i=1;$i<10;$i++) {
$checked = in_array($i, $already_selected) ? 'checked' : '';
echo '<input type="checkbox" name="products[]" value="' . $i . '" ' . $checked . '> '. $i .'<br>';
}
?>
<input type="submit">
</form>

How insert multiple rows in mysql table with php array? [duplicate]

This question already has answers here:
Best way to INSERT many values in mysqli?
(4 answers)
Closed 2 years ago.
I need to insert entries to mysql table from the form below.
1-form contains many rows.
2-entry will not be always consecutive in the rows (meaning row 1 can be empty and next row not)
3-all rows containing entries should be saved in the db table.
i want to INSERT INTO oz2ts_custompc_details (part_id, quantity, price)
Here is my entry form (custompc_form2.php)
<!DOCTYPE html>
<html>
<body>
<form action="../subs/custompcorder2.php/" method="post" id="form">
<p><input id="name" name="part_id[]"/>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><input id="name" name="part_id[]"/>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><input id="name" name="part_id[]"/>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><input id="name" name="part_id[]"/>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<input id="submit" type="submit" value="Submit Order" name="submission"/>
</form>
</body>
</html>
here is What I came up with but still not working.
here is the summary of how it is working: ||Rows 1 to 4 has data > all 4 are saved || row 1 is empty and rows 2 to 3 contains data > only rows 2 and 3 are saved not row 4|| Row 2 only has data all other are empty > Data not saved || Rows 2 and 3 has data > Row 2 only is saved
<?php
include '../db/connect.php';
foreach (array('part_id', 'quantity', 'price') as $pos) {
foreach ($_POST[$pos] as $id => $row) {
$_POST[$pos][$id] = mysqli_real_escape_string($con, $row);
}
}
$ids = $_POST['part_id'];
$quantities = $_POST['quantity'];
$prices = $_POST['price'];
$items = array();
$size = count($ids);
for($i = 0 ; $i < $size ; $i++){
// Check for part id
if (empty($ids[$i]) || empty($quantities[$i]) || empty($prices[$i])) {
continue;
}
$items[]=array(
"part_id" => $ids[$i],
"quantity" => $quantities[$i],
"price" => $prices[$i]
);
}
if (!empty($items)) {
$values = array();
foreach($items as $item){
$values[] = "('{$item['part_id']}', '{$item['quantity']}', '{$item['price']}')";
}
$values = implode(", ", $values);
$sql = "INSERT INTO oz2ts_custompc_details (part_id, quantity, price) VALUES {$values} ;
" ;
$result = mysqli_query($con, $sql );
if ($result) {
echo 'Successful inserts: ' . mysqli_affected_rows($con);
} else {
echo 'query failed: ' . mysqli_error($con);
}
}
?>
The first is a simplified entry form. The reel entry form looks like this:
<!DOCTYPE html>
<html>
<head></head>
<body>
<form action="../subs/custompcorder2.php/" method="post" id="form">
<div id="orderwrap">
<div id="orderheather">
<select id="platform" name="platform">
<option selected="selected" disabled="disabled">Select the
platform</option>
<option value="Intel">Intel</option>
<option value="AMD">AMD</option>
</select>
</div>
<div id="orderbody">
<p><select id="part_id" name="part_id[]">
<option selected="selected" disabled="disabled">Choose part1 </option>
<?php query() ?>
< /select>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><select id="part_id" name="part_id[]">
<option selected="selected" disabled="disabled">Choose part2 </option>
<?php query2() ?>
< /select>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><select id="part_id" name="part_id[]">
<option selected="selected" disabled="disabled">Choose part3 </option>
<?php query3() ?>
< /select>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><select id="part_id" name="part_id[]">
<option selected="selected" disabled="disabled">Choose part4 </option>
<?php query4() ?>
< /select>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<input id="submit" type="submit" value="Submit Order"name="submission"/>
</div>
</div>
</form>
</body>
</html>
Here is the php page containing function query(),query1(),..
<?php
include '../db/connect.php';
function query(){
global $con;
$myData=mysqli_query($con,"SELECT * FROM oz2ts_mijoshop_product");
while($record=mysqli_fetch_array($myData)){
echo'<option value="'.$record['product_id'].'">'.$record['model'].'</option>';
}
}
function query2(){
global $con;
$myData=mysqli_query($con,"SELECT * FROM oz2ts_mijoshop_product");
while($record=mysqli_fetch_array($myData)){
echo'<option value="'.$record['product_id'].'">'.$record['model'].'</option>';
}
}
function query3(){
global $con;
$myData=mysqli_query($con,"SELECT * FROM oz2ts_mijoshop_product");
while($record=mysqli_fetch_array($myData)){
echo'<option value="'.$record['product_id'].'">'.$record['model'].'</option>';
}
}
function query4(){
global $con;
$myData=mysqli_query($con,"SELECT * FROM oz2ts_mijoshop_product");
while($record=mysqli_fetch_array($myData)){
echo'<option value="'.$record['product_id'].'">'.$record['model'].'</option>';
}
}
function close(){
mysqli_close($con);
}
?>
Sanitize input correctly using array_map
Check for input before adding to array
Only run SQL if anything to be added
Use the following code:
<?php
include '../db/connect.php';
foreach (array('part_id', 'quantity', 'price') as $pos) {
foreach ($_POST[$pos] as $id => $row) {
$_POST[$pos][$id] = mysqli_real_escape_string($con, $row);
}
}
$ids = $_POST['part_id'];
$quantities = $_POST['quantity'];
$prices = $_POST['price'];
$items = array();
$size = count($ids);
for($i = 0 ; $i < $size ; $i++){
// Check for part id
if (empty($ids[$i]) || empty($quantities[$i]) || empty($prices[$i])) {
continue;
}
$items[] = array(
"part_id" => $ids[$i],
"quantity" => $quantities[$i],
"price" => $prices[$i]
);
}
if (!empty($items)) {
$values = array();
foreach($items as $item){
$values[] = "('{$item['part_id']}', '{$item['quantity']}', '{$item['price']}')";
}
$values = implode(", ", $values);
$sql = "INSERT INTO oz2ts_custompc_details (part_id, quantity, price) VALUES {$values} ;
" ;
$result = mysqli_query($con, $sql );
if ($result) {
echo 'Successful inserts: ' . mysqli_affected_rows($con);
} else {
echo 'query failed: ' . mysqli_error($con);
}
}
Here is a rough code, modify indeces by your own needs.
$ids = $_POST['part_id'] ;
$quantities = $_POST['quantity'] ;
$prices = $_POST['price'];
$items = array();
$size = count($names);
for($i = 0 ; $i < $size ; $i++){
$items[$i] = array(
"part_id" => $ids[$i],
"quantity" => $quantities[$i],
"price" => $prices[$i]
);
}
$values = array();
foreach($items as $item){
$values[] = "('{$item['part_id']}', '{$item['quantity']}', '{$item['price']}')";
}
$values = implode(", ", $values);
$sql = "
INSERT INTO oz2ts_custompc_details (part_id, quantity, price) VALUES {$values} ;
" ;
Here's an example of basic issue handling while inserting data. Included in error checks are
Confirm that we received all 3 fields - part_id, quantity and price
If there were 3 rows of part_id, there must be 3 rows of quantity and price
Add safety by preparing INSERT statement
Bind variables to the prepared statements
Pick up only those rows in which all 3 fields (part_id, quantity and price) were entered, and that they were valid numbers
Code that receives POST
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
// debug information. Let's find what the page is receiving
echo '<pre>', print_r($_POST, true), '</pre>';
$postedData = $_POST;
// confirm that we received all 3 fields - part_id, quantity, price
$fieldsReceived = true;
if ( !confirmFields('part_id')
|| !confirmFields('quantity')
|| !confirmFields('price')
) {
echo 'part_id, quantity or price has not been received. Exiting.';
exit;
}
// confirm that each of them have identical item-count
if ( count($postedData['part_id']) !== count($postedData['quantity'])
|| count($postedData['part_id']) !== count($postedData['price'])
) {
echo count($postedData['price_id']) .
' fields received for price_id, but different number of fields
were received for quantity or price. Please ensure that part_id,
quantity and price have the same number of fields. Exiting.';
exit;
}
// establish connection using mysqli_connect
$connection = mysqli_connect('localhost', 'user', 'pass', 'selected_db');
// prepare an insert statement
$sql = 'insert into oz2ts_custompc_details
(part_id, quantity, price) values
(?, ?, ?)';
$statement = mysqli_prepare($connection, $sql);
// bind integer, integer, double to the parameters in insert statement
// corresponding to the question marks
$part = 0;
$qty = 0;
$prc = 0.0000;
mysqli_stmt_bind_param($statement, 'iid', $part, $qty, $prc);
// loop through received data and only insert those that have valid values
// in part_id, quantity and price
$partsReceived = count($postedData['part_id']);
for ($i = 0; $i < $partsReceived; $i++) {
// if drop down boxes are used and default value for part is
// Choose part, let's see if user left the selection to default
// and ignore that line
if (strpos($postedData['part_id'][$i], 'Choose part') !== false) {
continue;
}
// do we have numeric data in current line?
// although not done here, one can check if part_id is integer (is_int)
// quantity is_int and price is_float before proceeding further
if ( !is_numeric($postedData['part_id'][$i])
|| !is_numeric($postedData['quantity'][$i])
|| !is_numeric($postedData['price'][$i])
) {
echo '<p>Entry # ' . ($i + 1) . '
will be ignored because of missing
or invalid part_id, quantity, or price</p>';
continue;
}
// update bind parameters
$part = $postedData['part_id'][$i];
$qty = $postedData['quantity'][$i];
$prc = $postedData['price'][$i];
// execute statement and move on to the next one
try {
mysqli_stmt_execute($statement);
echo '<p>Inserted part_id ' . $postedData['part_id'][$i] . '</p>';
} catch (Exception $e) {
echo '<p>Could not enter data with part_id '
. $postedData['part_id'][$i] . '<br>'
. 'Error ' . $e->getMessage() . '</p>';
}
}
// --------------------------
// FUNCTIONS
// --------------------------
/**
* Confirm that we received part_id, quantity and price from POST
*
* #param string $fieldName Name of the field to verify
*
* #return bool True if fieldname is set as an array; False otherwise
*/
function confirmFields($fieldName)
{
global $postedData;
return
(!isset($postedData[$fieldName]))
&& !is_array($postedData[$fieldName]) ? false : true;
}
?>

Passing radio button

In my form I am trying to get the radio checked value to be passed on to the next page (which is an FPDF page)
I have 4 options: Annual Leave, Sick Leave, Business Leave, & also others with a textfield.
However I have tried a lot of 'if' as well as 'switch cases'
I am getting either only the element with value '1'
or else 'Undefined index: rad in D:\xampp\htdocs\Application\generate_report.php on line 13'
some where I am wrong, can anyone help me please. My code below.
html form:
<form id="formmain" method="post" action="generate_report.php" onsubmit="return_validate()">
<script type="text/javascript">
function selectRadio(n){
document.forms["form4"]["r1"][n].checked=true
}
</script>
<table width="689">
<tr>
<td width="500d">
<input type="radio" name="rad" value="0" />
<label>Business Trip</label>
<input type="radio" name="rad" value="1"/><label>Annual Leave</label>
<input type="radio" name="rad" value="2"/><label>Sick Leave</label>
<input type="radio" name="rad" value="3"/><label>Others</label> <input type="text" name="others" size="25" onclick="selectRadio(3)" />​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
</td>
</tr>
</table>
//....
//below submit button is end of the html page:
<input type="submit" name="submit" value="send" />
</form>
Generate PDF form:
$radio = $_POST['rad']; // I am storing variable
if($radio = 0) {
$type = 'Business Leave';
}elseif ($radio = 1) {
$type = 'Annual Leave';
}elseif ($radio = 2) {
$type = 'Sick Leave';
} else { $type = $_POST['others']; }
//echo
$pdf->Cell(98,10, 'Reason | ' .$type , 1, 0, 'C', $fill);
if($radio = 0)
and
elseif ($radio = 1)
and all the other elseifs have to be == 1, with two '='!
A further explanation on the OP. If you do not use == then you are setting the value, not checking it. Furthermore, there are levels of checking. Using the double equals (==) is effectively stating "is equal to" whereas using triple equals (===) is like stating "is absolutely equal to". Generally the == operator will do everything you need but sometimes when working with data types or specific values you might need ===. This is mostly FYI as the OP has an actionable solution.
You should always check if inputs are checked or any value inserted. If there's no value, then it throws an undefined index error. Also, you should replace =s to == in your if clauses. So:
PHP:
$radio = $_POST['rad']; // I am storing variable
if (isset($radio)) { // checks if radio is set
if($radio == 0) {
$type = 'Business Leave';
}elseif ($radio == 1) {
$type = 'Annual Leave';
}elseif ($radio == 2) {
$type = 'Sick Leave';
} else {
if (isset($_POST['others'])) { // cheks if input text is set
$type = $_POST['others'];
}
else {
echo 'Error';
}
}
//echo
$pdf->Cell(98,10, 'Reason | ' .$type , 1, 0, 'C', $fill);
}
else {
echo 'Error';
}
Now it should work.

Categories