php form issues - php

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"/>

Related

retrieve 1 or more checkbox value from database

this is my html code
<input type='checkbox' name='cbox[]' value='Jaywalking' />
Jaywalking<br>
<input type='checkbox' name='cbox[]' value='Littering' />
Littering<br>
<input type='checkbox' name='cbox[]' value='Illegal Vendor' />
Illegal Vendor
this is my php code
if(isset($_POST['save']))
{
$license_save=$_POST['license'];
$stickerno_save=$_POST['stickerno'];
$fname_save=$_POST['fname'];
$mname_save=$_POST['mname'];
$lname_save=$_POST['lname'];
$no_save=$_POST['no'];
$street_save=$_POST['street'];
$city_save=$_POST['city'];
$bdate_save=$_POST['bdate'];
$violationplace_save=$_POST['violationplace'];
$dd_save=$_POST['dd'];
$mm_save=$_POST['mm'];
$yy_save=$_POST['yy'];
$hh_save=$_POST['hh'];
$min_save=$_POST['min'];
$ampm_save=$_POST['ampm'];
if(is_array($_POST['cbox'])) $violation_save=implode(',',$_POST['cbox']); else $violation_save=$_POST['cbox'];
mysql_query("UPDATE tblcitizen SET license ='$license_save', stickerno ='$stickerno_save', fname ='$fname_save', mname ='$mname_save', lname ='$lname_save', no ='$no_save', street ='$street_save', city ='$city_save', bdate ='$bdate_save', violationplace ='$violationplace_save', dd ='$dd_save', mm ='$mm_save', yy ='$yy_save', hh ='$hh_save', min ='$min_save', ampm ='$ampm_save', violation ='$violation_save', type ='$type_save', officer ='$officer_save', date ='$date_save', ttime ='$ttime_save' WHERE id = '$id'")
or die(mysql_error());
echo "<script>alert('Successfully Edited')</script>";
header("Location: citizen.php");
}
I want to edit some account registered, how can i retrieve 1 or more checkboxes value from the database.
EDITED FOR BETTER ANSWER
if(is_array($_POST['cbox'])) $violation_save=implode(',',$_POST['cbox']); else $violation_save=$_POST['cbox'];
Your query is taking the cbox array, turning it into a string with commas if it is an array (if more than one checkbox was checked), otherwise inserting just one checkbox value with no comma.
To get the values out, just read the string, then compare it with a php strpos()
<?
// Get the checkboxes that were previously selected
$result = mysql_query("SELECT violation FROM tblcitizen WHERE id = '$id'") or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
// put the string into a variable
$mystring = $row['violation'];
}
// use a ternary to determine if this checkbox exists
// if so, make the variable $checked to check the checkbox, otherwise leave it blank
$checked = (strpos($mystring, 'Jaywalking')) ? 'checked' : '';
?>
// write the checkbox to the page. and echo the contents of $checked
// if it was found with strpos() then it will be checked, otherwise it will not be
// <?= ?> is a quick way to echo a variable without the echo command
<input type='checkbox' name='cbox[]' value='Jaywalking' <?=$checked;?> />
I don't quite understand your sentence of "how can i retrieve 1 or more check boxes value from the database" but since I can see your update statement, I am assuming that you want to take the one or more value from the check boxes and update the table in the database.
You will receive the check box value in form of an array
You need to loop through the array and get the value
Store value in one variable and you are good to go to store it in the database
foreach ($cbox as $val) {
$Violation .= $val.",";
}
You can always remove the last comma using PHP substring by the way. Cheers, hope this helps you and anybody out there. Thank You.

Generate a query that changes a single element on multiple rows PHP MySQL

I'm working on a homework assignment that involves PHP. Basically, I have a page that contains a web form that renders items pulled from a database. There's checkboxes on each row and 2 radio buttons. The user selects "accept" or "deny" and when submit is clicked, the items that are checked are supposed to change to that approval status. All of the items in the form are submitted into post. I thought that post is an array so I could just use a while loop with a counter so that the loop traverses through the array and when it gets to the last index (which should contain approve or deny). A query is generated that changes all of the previous indexes to approve or deny. I'm sorry if this isn't making much sense.
Here's a picture for more clarification
Here's the code I used to generate the webform:
<?php
#create a query string
$query = "SELECT * FROM Request WHERE superemail = '$user'";
#echo $query;
#run the query
$result = mysqli_query($link, $query) or die('error querying');
while($row = mysqli_fetch_array($result)){
#print out each row of the queryi
#line up the query results with temporary strings
$change = $row['KEY'];
$name = $row['first']. " " . $row['last'];
#echo $name;
$email = $row['email'];
#echo $email;
$type = $row['type'];
#echo $type;
$duration = $row['duration'];
$status = $row['status'];
#create a table row with the query results
echo "<tr><td><input type=checkbox name=$change /></td>
<td>$name</td>
<td>$email</td><td>$type</td>
<td>$duration</td><td>$status</td></tr>";
} #end while
?>
<label for=update>Change status to:</label><br />
<input type=radio name=update value=A />Approved<br />
<input type=radio name=update value=D />Denied<br />
<input type = submit value = "Change Status" />
Each input tag (your checkboxes and your radio button) in your html should have a name attribute, such as: <input type='radio' name='accept' value='1' />. When the form is submitted and processed by PHP, your script will be able to access that info at $_POST['accept'] (or $_GET['accept'] depending on the form's method).
So you should be able to specify a name for the radio button, then check to see if there is a value in the POST array at that index.
I am going to assume a few things. First, that it is a design goal of yours to only process items in your approval queue that you choose to select, leaving the others alone. Second, that you want to change their status to what is chosen in a radio button. Third, that you want both a code snippet and an explanation as to how the task got accomplished.
So, here goes.
You have a series of checkboxes; I assume they have the same name. If you wish for the values to be passed to PHP as an array, you absolutely need to name the inputs whatever[] with emphatic emphasis on the []! This is what creates an array from the checkbox to appear in the $_POST/$_GET. Only those items selected will appear in the array. The value ought to be something useful (A value in the corresponding database table, say) which you can select for and query on...after sanitizing the input, of course.
So, your HTML input tag should look like this:
<input type="checkbox" name="process[]" value="<?php echo $employeeName ?>" >
You should have this coming back at you...
$_POST['process'][array(0=>name1, 1=>name2/*...etc*/)]
...which you can loop through with a foreach at your leisure.

Only my If statement gets activated, not my else, even if I don't provide an input for id

Here's my code, for some reason, whether I specify a value for the input id or not, it seems to provide one, because ONLY the if statement is run. Also, when I provide a value for the id (or not), nothing is updated or changed.
<?php
$culture = $_POST["culture"];
if (isset($_POST["id"])) {
$UID = $_POST["id"];
mysql_query("UPDATE culture SET cult_desc='$culture' WHERE cult_id=$UID");
echo $UID . " " . $culture . " If Statement Activated";
}
else {
mysql_query("INSERT INTO culture
VALUES(cult_desc='$culture')");
echo $culture . " Else Statement Activated";
}
?>
Here's the html code:
<form action="addculture.php" method="POST">
<span><input type="text" size="3" name="id" />
<input type="text" name="culture" />
<input type="submit" value="add" /></span>
</form>
If your ID value comes from an <input> field in the browser, then isset($_POST['fieldname']) will ALWAYS be true. An input field is always submitted the server, even if there is no data in it.
If you want to check if there's something in the field, then do this:
if (isset($_POST['id']) && ($_POST['id'] !== '')) {
...
}
That'll check if the id field actuall exists (which is should), and if it contains something OTHER than an empty string - all data coming out of $_POST/$_GET is a string, even if it's numeric data.
Try this if-statement instead:
if (isset($_POST["id"]) && trim($_POST["id"]) != "") {
If you post the data from a form and you have an input for id, I believe the id POST-variable will be set but empty.

How to get a list of unchecked checkboxes when submitting a form?

I have this code for example :
$b = "";
while ($row = mysql_fetch_array($rows)) {
if ($row['enabled'] == 1) {
$b = "checked";
} else {
$b = "":
}
echo "<\input name='nam[$row[id]]' type='checkbox' value='$row[id]' $b />";
}
When I execute this code, I will get a list of checkboxes, some of them are checked and others are not.
I can use this code to get a list of checked checkboxes.
if (isset($_POST['sub'])) { //check if form has been submitted or not
$nam = $_POST['nam'];
if (!empty($nam)) {
foreach($nam as $k=>$val){
// proccess operation with checked checkboxes
}
}
I need to know how I can get list of unckecked checkboxes after submitting the form.
Thanks in advance.
If the check boxes are dynamically created this is a trivial task:
Create a naming convention. For example, lets say that each checkbox is tied to a row in the DB, each row in the DB has a primary key. You can name each checkbox based off this key:
<input type="checkbox" id="foo_1" name="foo_1" />
<input type="checkbox" id="foo_2" name="foo_2" />
<input type="checkbox" id="foo_3" name="foo_3" />
Now when the form is submitted you can query the database to get the Id's and process the request as follows:
$res = mysql_query("select * from foo;");
while($row = mysql_fetch_array($res))
$checked = isset($_POST["foo_{$row['id']}");
...
}
Browsers send nothing for unchecked boxes, so your only hope is creating a hidden field that tells you the name of each checkbox (or add a hidden field for each checkbox).

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