form with array of checkboxes send incomplete data - php

I try to pass a form which contains other forms (same inside forms, dynamic) , but I have checked that the data which are sent to the 'script handler' (php) are incomplete data. I think somewhere buffer is overwriting or something. Here is the code :
<?php
if(isset($_POST['submit_num']))
{
$number=$_POST['sky'];
if($number== 0)
{
header('Location: /ceid_coffee/user_order_form.php');
}
else
{
$_SESSION['number'] = $number;
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");
while($row_rec = mysql_fetch_array($rec_result))
{
echo '<br>';
echo '<input type="checkbox" name="yliko[][$i]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';//<~~~~this line is form's data
}
echo '<br>';
}
echo '<input type="submit" name="submit" value="FINAL_ORDER">';
echo '</form>';
}
}
?>
And this is the handling script:
<?php
if (isset($_POST['submit']))
{
$number= $_SESSION['number'];
$item = $_SESSION['item'];
$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)'];
for($i=0;$i<$number;$i++)
{
$temp = $_POST['yliko'][$i]; // <~~~~ this line is the form's data
$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());
}
}
?>
This line here contains the data of each form , but i have echo them ($temp2) and i saw that they are incomplete.
$temp = $_POST['yliko'][$i];
If i select more than 1 checkbox for each item ($i) I get only one value from the checkboxes into the sql.
Do you see if I miss something ?

Ok i found the error. I replace this row :
echo '<input type="checkbox" name="yliko[][$i]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';//<~~~~this line is form's data
with this row :
echo '<input type="checkbox" name="yliko['.$i.'][]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';
I do not know how (i'm new to php) but it worked.

You will only get one value for each form because you are assigning the value of $i to each one:
echo '<input type="checkbox" name="yliko[][$i]" value='. etc.
is your problem line.
Have a look at the HTML that your code produces (ctrl-u in most browsers) and you will see why you get the wrong answer. All your checkboxes need to have unique names.
I would do it by assigning each checkbox a name that relates to the line in the database from which they are drawn eg:
name="checkbox_"'.$row['ylikaprimarykey']."etc.
This will get you up and running fairly quickly. For what it is worth, the ids of your table keys can give attackers information about your site so it is best practice to obfuscate them in some way. There are a number of excellent classes available free on the net that will do this for you.
If you really need to deal with what would have been in each form as a separate chunk of data, you can easily change the checkbox names vis:
name="checkbox_$formnumber_$obfuscatedkeynumber"
then loop through them with nested loops in your handling page.

Related

update checkboxes after submit

I am currently running into an issue, where I have this form consisting of checkboxes. I get the values of user preferences for the checkboxes from a database. Everything works great, and does what is supposed to do, however after I change and check some boxes and then hit the submit button, it will still show the old values to the form again. If I click again in the page again it will show the new values.
The code is shown below with comments.
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk
FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name
FROM categories
INNER JOIN portals on categories.portal_id=portals.portal_id
ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
<?php
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
if(isset($_POST['submit'])){
if(!empty($_POST['categories'])){
$cats= $_POST['categories'];
$result = mysqli_query($conn,$qry_del_usrcats); //delete all
for ($x = 0; $x < count($cats); $x++) {
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`)
VALUES ('".$_SESSION['user_id']."', '".$cats[$x]."');";
$result = mysqli_query($conn,$qry_add_usrcats);
}
echo "success";
}
elseif(empty($_POST['categories'])){ //if nothing is selected delete all
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
I am not sure what is causing to do that. Something is causing not to update the form after the submission. However, as i said everything works great meaning after i submit the values are stored and saved in the DB, but not shown/updated on the form. Let me know if you need any clarifications.
Thank you
Your procedural logic is backwards and you're doing a bunch of INSERT queries you don't need. As #sean said, change the order.
<?php
if(isset($_POST['submit'])){
if(isset($_POST['categories'])){
$cats= $_POST['categories'];
// don't do an INSERT for each category, build the values and do only one INSERT query with multiple values
$values = '';
for($x = 0; $x < count($cats); $x++) {
// add each value...
$values .= "('".$_SESSION['user_id']."', '".$cats[$x]."'),";
}
// trim the trailing apostrophe and add the values to the query
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`) VALUES ". rtrim($values,',');
$result = mysqli_query($conn,$qry_add_usrcats);
echo "success";
}
elseif(!isset($_POST['categories'])){ //if nothing is selected delete all
// you may want to put this query first, so if something is checked you delete all, so the db is clean and ready for the new data.
// and if nothing is checked, you're still deleting....
$qry_del_usrcats="DELETE FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name FROM categories INNER JOIN portals on categories.portal_id=portals.portal_id ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
Typically this occurs due to the order of your queries within the script.
If you want to show your updated results after submission, you should make your update or insert queries to be conditional, and have the script call itself. The order of your scripts is fine, but you just need to do the following:
Take this query:
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
and put it inside the if statement so it looks like this:
if (isset($_POST['submit'] {
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
$result = mysqli_query($conn,$qry_del_usrcats);
[along with the other updates you have]
}
Also, you will need to move this entire conditional above the form itself; typically any updates, inserts, or deletes should appear year the top of the form, and then call the selects afterward (outside of the conditional)

How to retrieve imploded array from a cell in an MySQL database through PHP

Thanks for taking the time to look at this question.
Currently, I have a piece of code that creates four checkboxes labeled as "Luxury, Brand, Retailer," and "B2B." I have looked into a number of PHP methods to create checkboxes, and I felt the implode() function was the most simple and suitable for my job. I have looked into a number of tutorials to create the implosions, however, they did not fit my criteria, as I would like the database values be reflected in the front-end. Currently in my database, the implode() works, therefore (for example), if I check "Luxury", "Brand", "Retailer", and press the "Submit" button, the three items "Luxury, Brand, Retailer" will be in that specified cell. It looks like my code works in the back-end, but these are my issues:
I am not exactly sure (despite multiple Googles) how to retrieve those values stored in the single-cell array, and have it selected as "selected" (this would "check" the box in the front-end)
Could someone kindly take a look at my code below and let me know what seems to be missing/wrong/erroneous so I could attempt the revisions? Anything would be appreciated, thank you!
<?
if (isset($_POST['formSubmit2'])){
$category = mysql_real_escape_string(implode(',',$_POST['category']));
$accountID = $_POST['accountID'];
mysql_query("UPDATE Spreadsheet SET category='$category' WHERE accountID='$accountID'");
}
$query = mysql_query("SELECT * FROM Spreadsheet LIMIT $firstRow,$rpp");
while($row = mysql_fetch_array($query)){
// Begin Checkboxes
$values = array('Luxury','Brand','Retailer','B2B');
?>
<form name ="category" method ="POST" action ="" >
<?
echo "<input type = 'hidden' name = 'accountID' value = '" . $row['accountID'] . "' >";
for($i = 0; $i < count($values); $i++){
?>
<input type="checkbox" name="category[]" value="<?php echo $values[$i]; ?>" id="rbl_<? echo $i; ?>" <? if($row['category'] == $i) echo "checked=\"checked\""; ?>/>
<? echo $values[$i] ?><br>
<? } ?>
<input type ="Submit" name ="formSubmit2" value ="Submit" />
</form>
<? } ?>
The best approach i can recommend given what you have is to, explode the values out of the db giving you a new array of all the select fields. Then use in_array to compare the list you have with this new list in the loop. then flag the checkboxs as needed.

Two values from an array checkbox

So I have a mysql table for the charges of a hospital. My program currently only gets the price of the checked procedure. But now, I also want to get the procedure name when it is checked.
transaction.php
while($row = mysql_fetch_array($result))
{
echo ' <tr> <td>'.$row[0].'</td> <td>'.$row[1].'</td><td>'.$row[2].'</td>';
$procedure=$row['procedure'];
echo '<td><input type="checkbox" name="er[]" value="$price."|".$procedure"></td>';
echo "</tr>";
}
echo '</table>';
computation.php
<?php
if(isset($_POST['er']))
{
$ercharge=$_POST['er'];
$totalofer = array_sum($ercharge);
}
if(isset($_POST['ultrasound']))
{
$x=$_POST['ultrasound'];
$totalofultrasound = array_sum($x);
}
if(isset($_POST['confinement']))
{
$y=$_POST['confinement'];
$totalofconfinement = array_sum($y);
}
$total = $totalofer + $totalofultrasound + $totalofconfinement;
$p = explode("|", $ercharge);
echo $p;
echo $total;
?>
It only gets the row for price. Can the value attribute have two values? I can't just make another checkbox cause that would be inappropriate.
edit: the explode function doesnt work. It says: Warning: explode() expects parameter 2 to be string, array given in C:\xampp\htdocs\computation.php on line 18
You should split your parameters in the HTML:
echo '<td><input type="checkbox" name="checked[$row_index][]" value="1">';
echo '<input type="hidden" name="prices[$row_index][]" value="$price">';
echo '<input type="hidden" name="procedures[$row_index][]" value="$procedure"></td>';
where $row_index is incremented on each row (tr tag)
By the way, explode will work on the items of the er array, not on the array itself. Try:
foreach ($er as $item) {
var_dump( explode( "|", $item ) );
}
I'm not sure I understand your question but couldn't you set the name attrtibute for your checkbox to the name of the procedure? It looks like you are setting the name to the er[] array but you never reference that later.

Keep selections in php generated form after submit (POST)

I'm currently using php to populate a form with selections from a database. The user chooses options in a select style form and submits this, which updates a summary of the selections below the form before a second submit button is used to complete the interaction.
My issue is that every time a user uses the first submit, the selections that were there previously do not stick. They have to go through the whole form again.
Is there anyway to keep these selections present without resorting to php if statements? There are a ton of options so it would be a pain to use php for each one. Also, form is being submitted via POST.
Sample from form:
<?php
// GRAB DATA
$result = mysql_query("SELECT * FROM special2 WHERE cat = 'COLOR' ORDER BY cat")
or die(mysql_error());
echo "<div id='color'><select id='color' name='product_color'>";
while($row = mysql_fetch_array( $result )) {
$name= $row["name"];
$cat= $row["cat"];
$price= $row["price"];
echo "<option value='";echo $name;echo"'>";echo $name;echo" ($$price)</option>";}
echo "</select>";
echo "<input type='hidden' name='amount_color' value='";echo $price;echo"'></div>";
?>
I tried using this js snippet to repopulate the selections, but it does not seem to work properly...
<script type="text/javascript">document.getElementById('color').value = "<?php echo $_GET['proudct_cpu'];?>";</script>
This does not seem to work. Any suggestions other than php if statements?
Thanks!
edit: This is basically the form set up I'm using, though I've shortened it significantly because the actual implementation is quite long.
// Make a MySQL Connection
<?php mysql_connect("localhost", "kp_dbl", "mastermaster") or die(mysql_error());
mysql_select_db("kp_db") or die(mysql_error());
?>
<br />
<form action="build22.php" method="post">
<input type="hidden" name="data" value="1" />
<br />
<br />
<?php
// GRAB DATA
$result = mysql_query("SELECT * FROM special2 WHERE cat = 'color' ORDER BY cat")
or die(mysql_error());
echo "<div id='color'><select id='color' name='product_color'>";
while($row = mysql_fetch_array( $result )) {
$name= $row["name"];
$cat= $row["cat"];
$price= $row["price"];
echo "<option value='";echo $name;echo"'>";echo $name;echo" ($$price)</option>";}
echo "</select>";
echo "<input type='hidden' name='amount_color' value='";echo $price;echo"'></div>";
?>
<input type="submit" value="Update Configuration">
</form>
The selections from the form above get echoed after submission to provide the user with an update as such:
<div id="config" style="background-color:#FFF; font-size:12px; line-height:22px;">
<h1>Current Configuration:</h1>
<?php echo "<strong>Color:</strong>&nbsp&nbsp&nbsp&nbsp";echo $_POST['product_color']; ?>
</div>
I assume you're storing the user's selections in a separate table. If that's the case, you'll need to add some logic to determine if you should display the form values or what's already been stored.
<?php
// form was not submitted and a config id was passed to the page
if (true === empty($_POST) && true === isset($_GET['config_id']))
{
// make sure to properly sanitize the user-input!
$rs = mysql_query("select * from saved_configuration where config_id={$_GET['config_id']}"); // make sure to properly sanitize the user-input!
$_POST = mysql_fetch_array($rs,MYSQL_ASSOC); // assuming a single row for simplicity. Storing in _POST for easy display later
}
?>
<div id="config" style="background-color:#FFF; font-size:12px; line-height:22px;">
<h1>Current Configuration:</h1>
<?php echo "<strong>Color:</strong>&nbsp&nbsp&nbsp&nbsp";echo $_POST['product_color']; ?>
</div>
So after storing the user's selections in the database, you can redirect them to the page with the new config_id in the URL to load the saved values. If you're not storing the selected values in a table, you can do something similar with cookies/sessions.
echo the variables into the value tag of the form elements. If you post all your code I'm sure I can help you.
UPDATE
ah, so they are dropdown lists that you need to remember what was selected? Apologies, I read your post in a rush yesterday and thought it was a form with text inputs.
I just did a similar thing myself but without trying your code let me see if I can help.
Basically what you need to do is set one value in the dropdown to selected="selected"
When I had to do this I had my dropdown values in an array like so:
$options = array( "stack", "overflow", "some", "random", "words");
// then you will take your GET variable:
$key = array_search($_GET['variablename'], $options);
// so this is saying find the index in the array of the value I just told you
// then you can set the value of the dropdown to this index of the array:
$selectedoption = $options[$key];
This is where it might be confusing as my code is different so if you want to use it you will probably need to restructure a bit
I have a doSelect function to which I pass the following parameters:
// what we are passing is: name of select, size, the array of values to use and the
// value we want to use as the default selected value
doSelect("select_name", 1, $options, $selectedoption, "");
// these are the two functions I have:
// this one just processes each value in the array as a select option which is either
// the selected value or just a 'normal' select value
FUNCTION doOptions($options, $selected)
{
foreach ($options as $option)
{
if ($option == $selected)
echo ("<option title=\"$title\" id=\"$value\" selected>$option</option>\n");
else
echo ("<option title=\"$title\" id=\"$value\">$option</option>\n");
}
}
// this is the function that controls everything - it takes your parameters and calls
// the above function
FUNCTION doSelect($name, $size, $options, $selected, $extra)
{
echo("<select class=\"\" id=\"$name\" name=\"$name\" size=\"$size\" $extra>\n");
doOptions($options, $selected);
echo("</select>\n");
}
I know that's a lot of new code that's been threw at you but if you can get your select values from the db into the array then everything else should fall nicely into place.
The only thing I would add, is at the start where we call doSelect, I would put that in an if statement because you don't want to set something as selected which hasn't been set:
if (isset($_GET['variable']))
{
$key = array_search($_GET['variablename'], $options);
$selectedoption = $options[$key];
doSelect("select_name", 1, $options, $selectedoption, "");
}
else
{
doSelect("select_name", 1, $options, "", "");
}
I hope that helps!

Inserting checkbox values into database

I have a form with several checkboxes which values are pulled from a database.
I managed to display them in the form, assign an appropriate value to each, but cannot insert their values into other database.
Here's the code:
<form id="form1" name="form1" method="post" action="">
<?php
$info_id = $_GET['info_id'];
$kv_dodatoci = mysql_query("SELECT * FROM `dodatoci`") or die('ERROR DISPLAYING: ' . mysql_error());
while ($kol = mysql_fetch_array($kv_dodatoci)){
$id_dodatoci = $kol['id_dodatoci'];
$mk = $kol['mk'];
echo '<input type="checkbox" name="id_dodatoci[]" id="id_dodatoci" value="' . $id_dodatoci . '" />';
echo '<label for="' . $id_dodatoci.'">' . $mk . '</label><br />';
}
?>
<input type="hidden" value="<?=$info_id?>" name="info_id" />
<input name="insert_info" type="submit" value="Insert Additional info" />
</form>
<?php
if (isset($_POST['insert_info']) && is_array($id_dodatoci)) {
echo $id_dodatoci . '<br />';
echo $mk . '<br />';
// --- Guess here's the problem ----- //
foreach ($_POST['id_dodatoci'] as $dodatok) {
$dodatok_kv = mysql_query("INSERT INTO `dodatoci_hotel` (id_dodatoci, info_id) VALUES ('$dodatok', '$info_id')") or die('ERROR INSERTING: '.mysql_error());
}
}
My problem is to loop through all checkboxes, and for each checked, populate a separate record in a database.
Actually I don't know how to recognize the which box is checked, and put the appropriate value in db.
You can tell if a checkbox is selected because it will have a value. If it's not selected, it won't appear in the request/get/post in PHP at all.
What you may want to do is check for the value of it and work based on that. The value is the string 'on' by default, but can be changed by the value='' attribute in HTML.
Here are a couple snippets of code that may help (not exactly production quality, but it will help illustrate):
HTML:
<input type='checkbox' name='ShowCloseWindowLink' value='1'/> Show the 'Close Window' link at the bottom of the form.
PHP:
if (isset($_POST["ShowCloseWindowLink"])) {
$ShowCloseWindowLink=1;
} else {
$ShowCloseWindowLink=0;
}
.....
$sql = "update table set ShowCloseWindowLink = ".mysql_real_escape_string($ShowCloseWindowLink)." where ..."
(assuming a table with a ShowCloseWindowLink column that will accept a 1 or 0)
As an extra note: You're using the wrong HTML syntax for IDs and <label>. <label>'s "for" attribute should point to an ID, not a value. You also need unique IDs for each element. The code you have posted would not validate.
Also, you're not validating your code at all. At the very least, do a htmlspecialchars() or htmlentities() on the input before you output it and a mysql_real_escape_string() before you insert data into the DB.
2nd Answer:
You might do something like this:
HTML:
echo '<input type="checkbox" name="id_dodatoci[]" value="'.$id_dodatoci.'" />';
PHP:
if ( !empty($_POST["id_dodatoci"]) ) {
$id_dodatoci = $_POST["id_dodatoci"];
print_r($id_dodatoci);
// This should provide an array of all the checkboxes that were checked.
// Any not checked will not be present.
} else {
// None of the id_dodatoci checkboxes were checked.
}
This is because you are using the same name for all of the checkboxes, so their values will be passed to php as an array. If you used different names, then each would have it's own post key/value pair.
This might help too:
http://www.php-mysql-tutorial.com/php-tutorial/using-php-forms.php
This is the loop that I needed. I realized that I need a loop through each key with the $i variable.
if(isset($_POST['id_dodatoci'])){
$id_dodatoci=$_POST['id_dodatoci'];
$arr_num=count($id_dodatoci);
$i=0;
while ($i < $arr_num)
{
$query="INSERT INTO `dodatoci_hotel`(id_dodatoci,info_id)
VALUES ('$id_dodatoci[$i]','$info_id')";
$res=mysql_query($query) or die('ERROR INSERTING: '.mysql_error());
$i++;
}
}
Well, as Eli wrote, the POST is not set, when a checkbox is not checked.
I sometimes use an additional hidden field (-array) to make sure, I have a list of all checkboxes on the page.
Example:
<input type="checkbox" name="my_checkbox[<?=$id_of_checkbox?>]">
<input type="hidden" name="array_checkboxes[<?=$id_of_checkbox?>]" value="is_on_page">
So I get in the $_POST:
array(2){
array(1){"my_checkbox" => array(1){[123]=>"1"}}
array(1){"array_checkboxes" => array(1){[123]=>"is_on_page"}}
}
I even get the second line, when the checkbox is NOT checked and I can loop through all checkboxes with something like this:
foreach ($_POST["array_checkboxes"] as $key => $value)
{
if($value=="is_on_page")
{
$value_of_checkbox[$key] = $_POST["my_checkbox"][$key];
//Save this value
}
}
Also something that few people use but that is quite nice in HTML, is that you can have:
<input type="hidden" name="my_checkbox" value="N" />
<input type="checkbox" name="my_checkbox" value="Y" />
and voila! - default values for checkboxes...!

Categories