post array keep only 1 value - php

PHP FORM CODE :
echo '<form name="planeSeat" action="koltuk-sec-process.php" method="post" >';
...
echo '<input type="checkbox" class="css-checkbox" id="'.$rightplace.'" name="artwork" value="'.$rightplace.'" />';
...
echo '<input type="submit" name="formSubmit" value="Üye girişi yapmadan devam et"/>';
PHP PROCESS CODE :
$rest1 = array();
$rest2 = array();
$rest1[] = htmlspecialchars($_POST["artwork"]);
$rest2[] = htmlspecialchars($_POST["artwork2"]);
if($rest1 != null){
print_r ($rest1);
}
if($rest2 != null){
print_r ($rest2);
}
When I send artwork, if I selected 2 checkboxes, $rest1 only keeps the last value. How can I send my all values?

You probably wanted to code
$rest1[] = htmlspecialchars($_POST["artwork"]);
$rest1[] = htmlspecialchars($_POST["artwork2"]);
instead of
$rest1[] = htmlspecialchars($_POST["artwork"]);
$rest2[] = htmlspecialchars($_POST["artwork2"]);

For one result, break should do the trick:
$foobar = array('uno', 'dos', 'tres');
foreach ($foobar as $fb) {
echo '<p>'.$fb.'</p>';
break;
}

the reason is simple : in case of multiple checkbox checked with the same name, you have to specified an array for the checkbox name, this way you will be able to traverse the posted values
echo '<input type="checkbox" class="css-checkbox" id="'.$rightplace.'" name="artwork[]" value="'.$rightplace.'" />';
echo '<input type="checkbox" class="css-checkbox" id="'.$rightplace.'" name="artwork[]" value="'.$rightplace.'" />'; // second checkbox
print_r ( $_POST['artwork'] ) // will display the artwork array
all of your checkbox with similar content should have the same name !!!!!

Related

Codeigniter - Edit Form with Checkbox

I'm using codeigniter and have a problem with my edit form in checkbox. The checkbox have 2 values 1 and 0, if checked then the value is 1 and if unchecked then the value is 0.
here is my controller:
function updatepost($id=0){
$data = $_POST;
$this->db->where('id_post',$id);
$outp = $this->db->update('post',$data);
}
And here is my view
sport <input type="checkbox" name="sport" value="1" <?php if($data['sport'] == '1'){echo 'checked';}?> />
tekno <input type="checkbox" name="tekno" value="1" <?php if($data['tekno'] == '1'){echo 'checked';}?>/>
game <input type="checkbox" name="game" value="1" <?php if($data['game'] == '1'){echo 'checked';}?>/>
if i unchecked the checkbox, value should be '0';
My question is how to get value if the checkbox is uncheked?
Many thanks for the answer..
Checkboxes are posted only if they are checked.
In your controller, check if they are posted,
if posted, value is 1 else 0.
Example Code:
$sport = 0;
if (! empty($_POST['sport']) {
$sport = 1;
}
If you want to use ternary operators, use:
$sport = (! empty($_POST['sport']) ? 1 : 0;
So, final code:
function updatepost($id=0){
// Assign default values in view that they are not getting
// posted if they are not checked.
// If they are posted, they will be overriden in $data.
$data['sport'] = $data['tekno'] = $data['tekno'] = 0;
$data = $_POST;
$this->db->where('id_post',$id);
$outp = $this->db->update('post',$data);
}
In your controller file replace the $data = $_POST; line by the following code
$data['sport'] = (array_key_exists('sport',$_POST)) ? $_POST['sport'] : 0;
$data['tekno'] = (array_key_exists('tekno',$_POST)) ? $_POST['tekno'] : 0;
$data['game'] = (array_key_exists('game',$_POST)) ? $_POST['game'] : 0;

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>

PhP Radio button in Array

I have a form where you can select a radio button and it should transfer what was selected to the next page. My problem is that no matter which radio button you choose it always transfers the value associated last radio button over instead of the one you chose.
So if I choose Around the World it carries 5 with it instead of 10
I am required to use the GET method.
Here is my code:
$title = array("Around the World"=>"10","Coast to Coast"=>"7","The Big City"=>"5");
foreach($title as $sub=>$s_value) {
echo "$sub $$s_value";
echo '<input type="radio" name="sub" value="', $sub,'">';
echo "<br>";
}
if (empty($_GET["sub"])) {
} else {
$sub = sub_input($_GET["sub"]);
}
if (empty($_GET["s_value"])) {
} else {
$s_value = sub_input($_GET["s_value"]);
}
if (isset($title['sub'])){
$valid=false;
}
This is the code for the next page:
echo "<b>$sub</b><br />";
echo "Base Total: $ $s_value/mon x $month months <br />";
Yes I have omitted a lot of things, because everything else in my code is fine.
I tried doing this as well, adding in an unset() statement but it didnt work. It completely deleted the value variable....
$title = array("Around the World"=>"10","Coast to Coast"=>"7","The Big City"=>"5");
foreach($title as $sub=>$s_value) {
echo "$sub $$s_value";
echo '<input type="radio" name="sub" value="', $sub,'">';
echo "<br>";
unset($s_value);
}
//I also tried putting the unset here//
if (empty($_GET["sub"])) {
} else {
$sub = sub_input($_GET["sub"]);
}
if (empty($_GET["s_value"])) {
} else {
$s_value = sub_input($_GET["s_value"]);
}
if (isset($title['sub'])){
$valid=false;
}
You need to change the names of your variables $s & $s_value within the foreach loop. The foreach loop is setting these variables and they are then being accessed outside of the foreach loop if either of the GET values is empty such that there is no GET value to replace the contents of the variable. Therefore, it always uses 5 as the value because that is the last $s_value that you set.
In summary, changing $s & $s_value within the foreach loop to something like $key & $value respectively will fix your problem with the array value. Alternatively, you could unset them after the foreach loop but before the if statements.
In your current code, you just happened to switched the values on the loop. 10, 7, 5 are inside the elements, while the names Around The world... etc are inside the keys. You just need to switch them. Consider this example:
<?php
$title = array("Around the World"=>"10","Coast to Coast"=>"7","The Big City"=>"5");
if(isset($_GET['submit'], $_GET['sub'])) {
$sub = $_GET['sub'];
$name = array_search($sub, $title);
echo '<script>alert("You selected '.$name. ' => '.$sub.'");</script>';
}
?>
<form method="GET" action="index.php">
<?php foreach($title as $key => $value): ?>
<input type="radio" name="sub" value="<?php echo $value; ?>" /> <?php echo $key; ?> <br/>
<?php endforeach; ?>
<br/>
<input type="submit" name="submit" value="Submit" />
</form>

multiple forms handled by one script php

I try to create an order page on php. I have created a form which stores data into the database. The form number is based on the user and it is created dynamic.
<?php
if(isset($_POST['submit_num']))
{
$number=$_POST['sky'];
for($i=0;$i<$number;$i++)
{
$item = $_SESSION['item'];
echo $item;
$rec_query = "SELECT * FROM ylika";
$rec_result= mysql_query($rec_query) or die("my eroors");
echo '<form action="user_order_form.php" method="POST">';
echo '<html>';
while($row_rec = mysql_fetch_array($rec_result))
{
echo '<input type="checkbox" name="yliko[]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';
echo '<br>';
}
echo '<br>';
echo '<input type="submit" name="submit" value="ORDER">';
echo '</form>';
}
}
?>
So I have many forms and 1 script to handle them. If I submit 1 form then it applies the data to the database but the other forms dissapear. This is the second php 'handler'.
<?php
if (isset($_POST['submit']))
{
$max_id = "SELECT MAX(id_order) FROM id_of_orders";
$x=mysql_query($max_id) or die("my eroors");
$id= mysql_fetch_array($x);
$xyz = $id['MAX(id_order)'];
$item = $_SESSION['item'];
$temp = $_POST['yliko'];
$temp2 = implode(",", $temp);
$inserts = ("INSERT INTO orders (order_id,product,ulika) VALUES ('$xyz' , '$item','$temp2')");
$inc_prod=("UPDATE proion SET Counter = Counter + 1 WHERE proion.onomasia='$item'");
mysql_query($inserts) or die(mysql_error());
mysql_query($inc_prod) or die(mysql_error());
}
?>
I want to submit all the forms. Should I try to create one submit button for all of the forms or is there a way to handle all of them separately ?
You can have many submit forms, but simply define one big <form> with all of them, then you will not lose any information.
<?php
if(isset($_POST['submit_num']))
{
$number=$_POST['sky'];
echo '<form action="user_order_form.php" method="POST">';
for($i=0;$i<$number;$i++)
{
$item = $_SESSION['item'];
echo $item;
$rec_query = "SELECT * FROM ylika";
$rec_result= mysql_query($rec_query) or die("my eroors");
echo '<html>';
while($row_rec = mysql_fetch_array($rec_result))
{
echo '<input type="checkbox" name="yliko[]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';
echo '<br>';
}
echo '<br>';
echo '<input type="submit" name="submit" value="ORDER">';
}
echo '</form>';
}
?>
now you can also add the ~$i~ identifier to input names, so you can easily distinguish which is which.

select all checkboxes if none are select in php query

I have a script wher users can find exercise from a database, I have checkboxes for the user to find specific exercises the script works fine when a least 1 checkbox is selected from each checkbox group however I would like it that if no checkboxes was selected then it would the results of all checkboxes.
my checkbox form looks like this
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="criteria">
<p><strong>MUSCLE GROUP</strong></p>
<input type="checkbox" name="muscle[]" id="abdominals" value="abdominals"/>Abdominals<br />
<input type="checkbox" name="muscle[]" id="biceps" value="biceps" />Biceps<br />
<input type="checkbox" name="muscle[]" id="calves" value="calves" />Calves<br />
ect...
<br /><p><strong>EQUIPMENT (please select a least one)</strong></p>
<input type="checkbox" name="equipment[]" id="equipment" value="bands"/>Bands<br />
<input type="checkbox" name="equipment[]" id="equipment" value="barbell" />Barbell<br />
<input type="checkbox" name="equipment[]" id="equipment" value="dumbbell" />Dumbbell<br />
ect....
<input type="submit" name="sub" value="Generate Query" />
</form>
and here is my script
<?php
if(isset($_POST['muscle']) && !empty($_POST['muscle'])){
if(isset($_POST['equipment']) && !empty($_POST['equipment'])){
//get the function
include ($_SERVER['DOCUMENT_ROOT'] .'/scripts/functions.php');
$page = (int) (!isset($_GET["page"]) ? 1 : $_GET["page"]);
$limit = 14;
$startpoint = ($page * $limit) - $limit;
// Runs mysql_real_escape_string() on every value encountered.
$clean_muscle = array_map('mysql_real_escape_string', $_REQUEST['muscle']);
$clean_equipment = array_map('mysql_real_escape_string', $_REQUEST['equipment']);
// Convert the array into a string.
$muscle = implode("','", $clean_muscle);
$equipment = implode("','", $clean_equipment);
$options = array();
if(array($muscle))
{
$options[] = "muscle IN ('$muscle')";
}
if(array($equipment))
{
$options[] = "equipment IN ('$equipment')";
}
$fullsearch = implode(' AND ', $options);
$statement = "mytable";
if ($fullsearch <> '') {
$statement .= " WHERE " . $fullsearch;
}
if(!$query=mysql_query("SELECT * FROM {$statement} LIMIT {$startpoint} , {$limit}"))
{
echo "Cannot parse query";
}
elseif(mysql_num_rows($query) == 0) {
echo "No records found";
}
else {
echo "";
while($row = mysql_fetch_assoc($query)) {
echo "".$row['name'] ."</br>
".$row['description'] ."";
}
}
echo "<div class=\"new-pagination\">";
echo pagination($statement,$limit,$page);
echo "</div>";
}
}
Im new with php so my code may not be the best. If anyone can help me or point me in the right direction I would be very greatful.
OK - I think I have figured it all out. You were right - the main problem was in your isset and isempty calls. I created some variations on your file, and this shows what is going on. Note - since I don't have some of your "other" functions, I am only showing what is going wrong in the outer parts of your function.
Part 1: validating function
In the following code, I have added two JavaScript functions to the input form; these were loosely based on scripts you can find when you google "JavaScript validation checkbox". The oneBoxSet(groupName) function will look through all document elements; find the ones of type checkBox, see if one of them is checked, and if so, confirms that it belongs to groupName. For now, it returns "true" or "false". The calling function, validateMe(formName), runs your validation. It is called by adding
onclick="validateMe('criteria'); return false;"
to the code of the submit button. This basically says "call this function with this parameter to validate the form". In this case the function "fixes" the data and submits; but you could imagine that it returns "false", in which case the submit action will be canceled.
In the validateMe function we check whether at least one box is checked in each group; if it is not, then a hidden box in the "all[]" group is set accordingly.
I changed the code a little bit - it calls a different script (muscle.php) instead of the <?php echo $_SERVER['PHP_SELF']; ?> you had... obviously the principle is the same.
After this initial code we will look at some stuff I added in muscle.php to confirm what your original problem was.
<html>
<head>
<script type="text/javascript">
// go through all checkboxes; see if at least one with name 'groupName' is set
// if so, return true; otherwise return false
function oneBoxSet(groupName)
{
var c=document.getElementsByTagName('input');
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].checked) {
if (c[i].name == groupName) {
return true; // at least one box in this group is checked
}
}
}
}
return false; // never found a good checkbox
}
function setAllBoxes(groupName, TF)
{
// set the 'checked' property of all inputs in this group to 'TF' (true or false)
var c=document.getElementsByTagName('input');
// alert("setting all boxes for " + groupName + " to " + TF);
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].name == groupName) {
c[i].checked = TF;
}
}
}
return 0;
}
// this function is run when submit is pressed:
function validateMe(formName) {
if (oneBoxSet('muscle[]')) {
document.getElementById("allMuscles").value = "selectedMuscles";
//alert("muscle OK!");
}
else {
document.getElementById("allMuscles").value = "allMuscles";
// and/or insert code that sets all boxes in this group:
setAllBoxes('muscle[]', true);
alert("No muscle group was selected - has been set to ALL");
}
if (oneBoxSet('equipment[]')) {
document.getElementById("allEquipment").value = "selectedEquipment";
//alert("equipment OK!");
}
else {
document.getElementById("allEquipment").value = "allEquipment";
// instead, you could insert code here that sets all boxes in this category to true
setAllBoxes('equipment[]', true);
alert("No equipment was selected - has been set to ALL");
}
// submit the form - function never returns
document.forms[formName].submit();
}
</script>
</head>
<body>
<form action="muscle.php" method="post" name="criteria">
<p><strong>MUSCLE GROUP</strong></p>
<input type="checkbox" name="muscle[]" id="abdominals" value="abdominals"/>Abdominals<br />
<input type="checkbox" name="muscle[]" id="biceps" value="biceps" />Biceps<br />
<input type="checkbox" name="muscle[]" id="calves" value="calves" />Calves<br />
<input type="hidden" name="all[]" id="allMuscles" value="selectedMuscles" />
etc...<br>
<br /><p><strong>EQUIPMENT (please select a least one)</strong></p>
<input type="checkbox" name="equipment[]" id="equipment" value="bands"/>Bands<br />
<input type="checkbox" name="equipment[]" id="equipment" value="barbell" />Barbell<br />
<input type="checkbox" name="equipment[]" id="equipment" value="dumbbell" />Dumbbell<br />
<input type="hidden" name="all[]" id="allEquipment" value="selectedEquipment" />
<br>
<input type="submit" name="sub" value="Generate Query" onclick="validateMe('criteria'); return false;" />
</form>
</body>
</html>
Part 2: what's wrong with the PHP?
Now here is a new start to the php script. It checks the conditions that you were testing at the start of your original script, and demonstrates that you never get past the initial if statements if a check box wasn't set in one of the groups. I suggest that you leave these tests out altogether, and instead get inspiration from the code I wrote to fix any issues. For example, you can test whether equipmentAll or muscleAll were set, and create the appropriate query string accordingly.
<?php
echo 'file was called successfully<br><br>';
if(isset($_POST['muscle'])) {
echo "_POST[muscle] is set<br>";
print_r($_POST[muscle]);
echo "<br>";
if (!empty($_POST['muscle'])) {
echo "_POST[muscle] is not empty!<br>";
}
else {
echo "_POST[muscle] is empty!<br>";
}
}
else {
echo "_POST[muscle] is not set: it is empty!<br>";
}
if(isset($_POST['equipment'])) {
echo "_POST[equipment] is set<br>";
print_r($_POST['equipment']);
echo "<br>";
if (!empty($_POST['equipment'])) {
echo "_POST[equipment] is not empty!<br>";
}
else {
echo "_POST[equipment] is empty!<br>";
}
}
else {
echo "_POST[equipment] is not set: it is empty!<br>";
}
if(isset($_POST['all'])) {
echo "this is what you have to do:<br>";
print_r($_POST['all']);
echo "<br>";
}
// if(isset($_POST['muscle']) && !empty($_POST['muscle'])){
// if(isset($_POST['equipment']) && !empty($_POST['equipment'])){
If you call this with no check boxes selected, you get two dialogs ('not OK!'), then the following output:
file was called successfully
_POST[muscle] is not set: it is empty!
_POST[equipment] is not set: it is empty!
this is what you have to do:
Array ( [0] => allMuscles [1] => allEquipment )
If you select a couple of boxes in the first group, and none in the second:
file was called successfully
_POST[muscle] is set
Array ( [0] => abdominals [1] => calves )
_POST[muscle] is not empty!
_POST[equipment] is not set: it is empty!
this is what you have to do:
Array ( [0] => selectedMuscles [1] => allEquipment )
I do not claim to write beautiful code; but I hope this is functional, and gets you out of the fix you were in. Good luck!

Categories