Inserting checkbox values into database - php

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...!

Related

How to understand who checkbox is selected?

i want to select a lot row of my database and have checkbox to any of rows that the user can choose any of them.then i should update database according to user choice, but i can't understand who of this checkbox is selected.
thanks a lot...
the semicode is here:
$query = "Select * mytable limit 30;";
$res = $mysql->ExecuteStatement (array ());
echo '<form method="post" action=""> ';
$b=0;
while ($rec=$res -> fetch())
{
echo '<input type="checkbox" id="$b" name="checkboxName[]" value="yes"/>';
$checkboxID = "number_".$rec["ID"].":";
echo $checkboxID;
echo $rec["column1"]."</br>";
$b++;
}
if(isset($_POST['formSubmit'])) //this code just get us how many of checkbox are chosen not who are chosen
{
foreach($_POST['checkboxName'] as $selected)
{
echo $selected."</br>";
}
}
Try some thing like this:
Provide a class to all checkboxes:
<input type="checkbox" class="MyChkbox" id="$b" name="checkboxName[]" value="yes"/>';
In JS:
$('.MyChkbox').click(function(){
if($(this).is(':checked'))
{
var checkedId = $(this).attr('id');
// checkedId will contain the checked checkbox id in it. Use it as per your need
}
});
Hi In these case you should pass the Id of row as value of Checkbox and then get them when form is posted so you can try this
echo '<td><input type="checkbox" class="MyChkbox" id="$b" name="checkboxName[]" value="' . $rec["ID"] . '"></td>';
these will have value as row ID

How to fill an HTML Form with (a lot) of records from database?

I've a HTML form with approx. 120 input text fields.
Then i've a PHP page with the same form where i've this code to show the value get from database.
<input type="text" id="field_1" name="field_1" value="<?php echo $myvalue1; ?>" />
Is there a way to retrieve data from database and fill the input text value for each field or doing it in a better way than specify more than 120 variables?
Thanks!
There's a trick in PHP. You can name your inputs using "[]" operator. like this:
<input type="text" id="field_1" name="field[]" value="<?php echo $myvalue1; ?>" />
As the result it will be treated as an array in the corresponding REQUEST array (POST or GET, depends of HTTP method for you form).
To fill the inputs, simply use a loop.
You can always store the results in an array, then loop through that.
$q = mysql_query ( ... );
for ($i = 1; $r = mysql_fetch_row ($q); ++$i)
printf ('<input tyle="text" id="field_%s" name="field_%s" value="%s"/>', $i, $i, $r[0]);
Loop through your results from the query and generate textboxs
<?php
$sql = "SELECT column FROM table";
if ($result = $mysqli->query($sql)) {
while($obj = $result->fetch_object()){
echo "<input type='text' name='field[]' value='". $obj->column ."'> <br>"; // Here is the where you put your textbox in loop
}
}
$result->close();
?>

form with array of checkboxes send incomplete data

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.

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.

php form issues

I have a form with which I am trying to display a form with checkboxes, and then insert into a database whether or not those checkboxes are checked. Then, each time the page is called, check the value and append information to the html form to appropriate display the checkbox as checked or not.
I have modified the below code example to make it short, and I am aware that I am assigning the checked value to 'value', which won't do anything.
The approach of
<input type="checkbox" name="notice" value="checked" checked/>
to display a checkbox as checked, while not valid html, works in every browser, and is based on the example here. I would prefer to stick with this approach.
Now, I don't see what is wrong with my code.
The first steps should be to retrieve the values from the database, of which onyl one row will be retrieved, as article_no is a primary key. If nothing is retrieved, then the variables are simply assigned "", which results in the checkbox being unchecked.
As the value is checked, if it is selected, this should be inserted into the database, and will show as checked upon next viewing of the page.
Now, as it is, this code compeltely fails. firebug does not show anything being sent or received in the console, no erros are recorded either with php or mysql, nothing appears in the database despite the fields and such being correct, no mysql errors are reported...
What is the problem?
The code:
<?php
error_reporting(E_ALL);
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"];
else
if (isset($_POST["cmd"]))
$cmd = $_POST["cmd"];
if (isset($_GET["pk"]))
{ $pk = $_GET["pk"];}
if (isset($_POST["deleted"]))
{ $deleted = $_POST["deleted"];}
if (isset($_POST["notice"]))
{ $notice = $_POST["notice"];}
$con = mysqli_connect("localhost","user","pass", "db");
if (!$con) {
echo "Can't connect to MySQL Server. Errorcode: %s\n". mysqli_connect_error();
exit;
}
$con->set_charset("utf8");
$getformdata = $con->query("select * from TEST where ARTICLE_NO = '$pk'");
$checkDeleted = "";
$checkNotice = "";
while ($row = mysqli_fetch_assoc($getformdata))
{
$checkDeleted = $row['deleted'];
$checkNotice = $row['notice'];
}
if($cmd=="submitinfo"){
$statusQuery = "INSERT INTO TEST VALUES (?, ?, ?)";
if ($statusInfo = $con->prepare($statusQuery)) {
$statusInfo->bind_param("sss", $pk, $deleted, $notice);
$statusInfo->execute();
$statusInfo->close();
} else {
print_r($con->error);
}
}
echo "<form name=\"statusForm\" action=\"x.php\" method=\"post\" enctype=\"multipart/form-data\">
<h1>Editing information for auction: ".$pk."</h1>
Löschung Ebay:
<input type=\"checkbox\" name=\"deleted\" value=\"checked\" ".$checkDeleted." align=\"right\"/>
<br />
Abmahnung:
<input type=\"checkbox\" name=\"notice\" value=\"checked\" ".$checkNotice." align=\"left\"/>
<br />
<input type=\"hidden\" name=\"cmd\" value=\"submitinfo\" />
<input name=\"Submit\" type=\"submit\" value=\"submit\" />
</form>";
In the actual form/page, I have appropriate sanitization in place.
A big problem is that nothing is being inserted into the database and no errors are being returned at all!
It's important to remember that unchecked checkbox does not contribute any values to a form when it is sent. When the deleted box is unchecked, there is no $_POST['deleted'] value set.
With that in mind, it looks like you don't actually set the value of $deleted if the checkbox is cleared. Use an idiom like this.
$deleted = isset($_POST["deleted"]) ? 1: 0;
Substitute the 1 and 0 with whatever values you want in your database table for the checked and unchecked states (in your case, "checked" and "")
Along the same lines as Paul Dixon's answer, I've done this at times:
<input type="hidden" name="notice" value="not checked" />
<input type="checkbox" name="notice" value="checked" checked="checked" />
If the user unchecks the checkbox, the hidden input's value gets sent instead. This way, $_POST['notice'] is always sent to your script.
I thought checkboxes should be done this way:
<input type="checkbox" name="notice1" value="value1" checked="checked"/>
<input type="checkbox" name="notice2" value="value2" checked="checked"/>

Categories