I've got a set of checkboxes but one shuld be always checked, I want that this checkbox is also hidden from my page, I need this beacause I have the DB that can be read only if this attribute is checked..
Please I need answers where you teach me how to hide the checkbox and NOT where you say that I can change the comand on SQL
$sqlPers= "SELECT * FROM personalizzazione";
$countPers = 0;
foreach ($dbh->query($sqlPers) as $rowPers){
$selez = '';
if($rowPers['Condimento'] == 'Base')
$selez = " checked = 'checked' ";
echo "<div class='checkbox'><label class='bianco'><input type='checkbox'" .
$selez . "name='".$rowPizza["idPizze"]."_".$rowPers["idPersonalizzazione"].
"' id='".$rowPizza["idPizze"]."_".$rowPers["idPersonalizzazione"]."'>".
$rowPers['Condimento']." (€ ".$rowPers['Prezzo'].")</label></div>";
$countPers++;
}
I tried to add type = 'hidden' in the variable $selez but nothing
Otherwise can someone say me how to disable it or hide it throught ccs?
I've tried searching on internet and there weren't full solutions for my question
There are two things you can do:
Method 1 - Hide it using CSS:
<input type='checkbox' style='display:none;'>
Method 2 - Use a hidden type instead of checkbox:
Another option would not have a checkbox, but rather have a separate hidden input tag.
<input type='hidden' name='pizza' value='value'>
You can hide it with style="display:none;"
But since it is hidden, does it have to be a checkbox?
A regular hidden input would do the job, too.
Look at the HTML that gets sent to the browser: You have already set type='checkbox' in your string, so having an additional type='hidden' may not give you what you want. You end up with <input type='checkbox' type='hidden'...
Your error was tough to see because you're writing your code in a way that is really difficult to debug. It's better practice to do all the logic up front. You're better off building all the attributes in code first. For example:
//run test to make $hide true for the loop where you want to hide the checkbox
$type = 'checkbox';
$style = $hide? "display:none" : "";
$name = $id = "$rowPizza[idPizze]_$rowPers[idPersonalizzazione]";
...
//then later when you can build your html
$html = "<div class='checkbox'><label class='bianco'><input type='$type' name='$name' id='$id' style='$style'>";
//Finally once you've built the whole html you can echo it
echo $html;
Note that we set display:none style when the $hide variable is true. Otherwise, the style will just be an empty string and the checkbox will be shown
Related
I have a MySQL database with auto-increment column "line numbers." In the form that is being submitted to the script, there are check boxes. I don't know how many check boxes there are, because each Customer has a different number of services that they're allowed to access. When the check box is clicked, they've used a service and the integer in column Available for that row needs to decrease by one. Sometimes, the user can say that multiple services were used and more than one row needs to be affected.
Where I'm becoming stuck is on two things: how the check boxes are named, and if I name them by the line number, how to access them with PHP.
while($cell = mysqli_fetch_array($service_details_query)) {
echo "</br>";
echo "<input type='checkbox' name='" . $cell['line_item'] . "'>";
}
The above code is how I'm making the check box. Probably the biggest part of the question is how I could better name it so that I can predict what names to look for ($_POST[name]) when the form is submitted (instead of a random number).
The other part I'm getting stuck on is, if I do decide to keep the naming strategy, how to fetch it. What I've thought of is to use a loop to extract the true/false data that's carried, but I don't know how to execute that. Sure, I can write a for or while loop, but I don't know how to extract the name of the object.
Is there any way I could carry extra data to a PHP script, other than the name?
Is there a better way I could name the check box so that I'm not stuck having to figure out a complicated way of finding the data, retrieving the name, etc.
I'm sort of a beginner when it comes to PHP. I know how to get my way around with for loops, while loops, basic commands such as echo... but I'm really lacking
while($cell = mysqli_fetch_array($service_details_query)) {
echo "</br>";
echo "<input type='checkbox' name='checkboxname[]' value ='".$cell['line_item']."'>";
}
It should do a $_POST array with the name checkboxname inside that array, you find the values.
You can find it threating $_POST['checkboxname'] as an array.
Try name it like: "checkbox_" . $cell['line_item'] so you can do something like this:
foreach($_POST as $name => $value)
{
if(substr($name, 9) == "checkbox_"){
//USE the value
}
}
or you could name like this:
echo "<input type='checkbox' name='services[]' value='" . $cell['id'] . "'>";
and get it as an array like this: $services = $_POST["services"];
Alright. Since you wanted to be able to add extra data, I thought I'd start over complicating stuff a lot! But it does the job. Explanation can be found in the codes comments.
First the HTML and Javascript part:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
// First we need to get our form
var myForm = document.getElementById("myForm");
// Next we're adding an event listener to the form submit so we can catch it
// and use a function to do some stuff before sending it over to the php file
myForm.addEventListener("submit", function(event){
// Now we need to temporarely stop the form from submitting
event.preventDefault();
// Next we need to get all our checkboxes
var checkBoxes = document.getElementsByClassName("myCheckbox");
// Now we need some arrays for all the data we're going to send over
// Basicly you make one for each data attribute
var lineNr = [];
var someThing = [];
// Lets loop through all checkboxes
for (var i=0; i<checkBoxes.length; i++) {
// Catch the ones checked
if (checkBoxes[i].checked) {
// Push the data attribute values to the arrays
lineNr.push(checkBoxes[i].dataset.linenr);
someThing.push(checkBoxes[i].dataset.something);
}
}
// Now we to JSON encode these arrays to send them over to PHP
var jsonLineNr = JSON.stringify(lineNr);
var jsonSomeThing = JSON.stringify(someThing);
// Since we cannot directly add these variables to our form submit,
// unless we use Ajax, we need to add them to our form in some
// hidden fields
myForm.innerHTML += "<input type='hidden' name='jsonLineNrs' value='"+ jsonLineNr +"' />";
myForm.innerHTML += "<input type='hidden' name='jsonSomeThings' value='"+ jsonSomeThing +"' />";
// All done, now we submit our form
myForm.submit();
}
</script>
</head>
<body>
<form method="POST" action="your_php_file.php" id="myForm" accept-charset="utf-8">
<input type="checkbox" class="myCheckbox" data-linenr="1" data-something="value1" />
<br />
<input type="checkbox" class="myCheckbox" data-linenr="2" data-something="value2" />
<br />
<input type="checkbox" class="myCheckbox" data-linenr="3" data-something="value3" />
<br />
<input type="submit" value="Submit" />
</form>
</body>
</form>
Next the PHP part:
<?php
// First we need to decode the JSON strings so we can use them
$jsonLineNrs = json_decode($_POST['jsonLineNrs']);
$jsonSomeThings = json_decode($_POST['jsonSomeThings']);
// Now both of those variables are arrays that contain all the data you wanted
// You can loop each of them to do stuff like
foreach($jsonLineNrs as $jsonLineNr){
echo $jsonLineNr; //Will echo out each line number
}
// Or if you want to loop through both simultaneously so you can
// keep each checked box data values together:
for($i=0; $i<count($jsonLineNrs)-1; $i++) {
echo $jsonLineNrs[$i].' - '.$jsonSomeThings[$i];
}
?>
Now before I finish this answer, one last warning: I didn't sanitize the user input in the Javascript part. It would make this answer even a lot more complicated and way to long. Be sure to do this, as you can NEVER EVER trust user input! Even if it's only checkboxes, POST data can be changed before it's submitted!
I would prefix the names depending on context, for example:
<input type='checkbox' name='service_" . $cell['line_item'] . "'>"
This way, if the checkbox represents a service, you could identify it by the prefix.
I have a check box list which I fill it with data from my table.Here is the code:
<?php
mysql_connect("localhost","root","");
mysql_select_db("erp");
$a="Select * from magazine";
$b=mysql_query($a);
$c=mysql_fetch_array($b);
while($c=mysql_fetch_array($b))
{
print '<input type="checkbox"/>'.$c['den_mag'];
echo "</br>";
}
if(isset($_POST['den_mag']))
{
echo "aaaa";
}
?>
It's a simple query and for each data just show it with a checkbox.Now what I want is when I press a checkbox the value of that checkbox to be shown in a table.So if I have check1 with value a , check2 with value b and I check check1 the value a to be outputted to a table row.How can I achieve that? how cand I get which checkbox is checked?
A few notes:
Try to avoid using SELECT * queries. Select the fields you are going to use:
$sql= '
SELECT
id,
den_mag
FROM
magazine
';
Use better variable names. $a and $c make your code harder to follow for others, and for yourself when you come back at a later time. Use more descriptive variable names like $query_object and $row. Your code should read almost like an essay describing what you're doing.
In your form, use an array of elements. By giving the input a name like selected_magazines[], you will end up with an array in your post data, which is what you want -- multiple selections
Use the row ID as the value of the checkbox element. Your array in POST will then be a list of all the IDs that the user selected
Separate your logic from your HTML generation. The top portion of your script should take care of all logic and decisions. At the bottom, output your HTML and avoid making logical decisions. It makes for a script that is easier to follow and maintain, as well as debug.
Here is a sample script incorporating these ideas with the details you've given:
<?php
// FILE: myfile.php
mysql_connect("localhost","root","");
mysql_select_db("erp");
if(isset($_POST['selected_magazine'])) {
// $_POST['selected_magazine'] will contain selected IDs
print 'You selected: ';
print '<ul><li>'.implode($_POST['selected_magazine'], '</li><li>').'</li></ul>';
die();
}
$sql= '
SELECT
`id`,
`den_mag`
FROM
`magazine`
';
$query_object=mysql_query($sql);
$checkboxes = array();
while($row = mysql_fetch_array($query_object)) {
$checkboxes[] = '<input name="selected_magazine[]" value="'.$row['id'].'" type="checkbox" /> '.$row['den_mag'];
}
?>
<form action="myfile.php" method="post">
<?php print implode('<br>', $checkboxes); ?>
<input type="submit" value="Submit" />
</form>
<input name="test" type="checkbox" />
<?php
if(isset($_REQUEST['test'])){
// selected
}
?>
When you give input-type elements (input, textarea, select, button) a name attribute (like I did), the browser will submit the state/value of the element to the server (if the containing form has been submitted).
In case of checkboxes, you don't really need to check the value, but just that it exists. If the checkbox is not selected, it won't be set.
Also, you need to understand the client-server flow. PHP can't check for something if the client does not send it.
And finally, someone mentioned jQuery. jQuery is plain javascript with perhaps some added sugar. But the point is, you could in theory change stuff with jQuery so that it gets (or doesn't get) submitted with the request. For example, you could get jQuery to destroy the checkbox before the form is submitted (the checkbox won't be sent in this case).
Here you go :
<html>
<input name="test" value="true" type="checkbox" />
</html>
<?php
$Checkbox1 = "{$_POST['test']}";
if($Checkbox1 == 'true'){
// yes, it is checked
}
?>
I have a form that submits multiple values using php. code is below:
echo "<form action='?ud=".$ud."' method='post'>Name: <input type='text' name='fname' />";
$resultw = mysql_query("SELECT * FROM options where userid='$ud' ORDER BY priority ASC");
while($row = mysql_fetch_array($resultw))
{
echo "
<input type='hidden' name='widgetid[]' value='".$row['widgetid']."' />
<span id='".$row['widgetid']."' style='color:white;font-size:13px;'>".$row['items'] . "</span><br></div><div style='' class='portlet_content'>
Enabled <input title='Enabled/Disabled' type='checkbox' value='enable[]' name='enable[]' ".$checked." id='checkbox".$row['id']."' />
Height <input title='set height' name='height[]' value='".$row['height']."' type='text' name='textfield' id='textfield".$row['id']."' />
";
}
echo '<input type="submit" /></form>';?>
as you can see its a loop thats get the values from db and echoes a form. I made it as simple as possible it has more input boxes but i removed them and removed the styling to make it simpler to read. when I hit Submit I would like to be able to have all those values updated to the database through a loop.
I tried foreach and struggled. any suggestions
First of all, your code has a security bug in that you are directly putting a variable into a SQL query. That allows for SQL injection. Instead, you should put the variable $ud through mysql_real_escape_string before inserting into the query or, significantly better, use MySQLi/PDO and prepared statements.
Have you checked that the form is correctly echoed onto the page? View the source (or use Firefox and Firebug) to double check that it has been properly inserted.
Then you will need to have a code block that is initiated when it receives a POST request. That code will get an array back for each of your variables e.g.
$widget_ids = $_POST['widgetid']; #this will be an array
$enable = $_POST['enable'];
$height = $_POST['height'];
You can do this for each of your POSTed variables and then just loop round the widget ids doing an update query for each one e.g.
$i = -1;
foreach($widget_ids as $widget_id) {
$row_enable = $enable[++$i];
$row_height = $height[$i];
//DO THIS FOR THE REST AND THEN YOUR UPDATE QUERY
}
Just to be pedantic, your HTML is also a bit messy and incorrect. For a form I would use label elements for each label and don't use br's for new lines. You also have a div with no beginning and then a div with no ending.
I have two forms
a) post.php
b) edit.php
I am using the checkbox in both the form to set the binary value (0 and 1) to set the status for approve.
to process the value from the checkbox in the post.php I am using the code which checks and assume that if the checkbox is checked then the value will be 1 other wise it is 0 by default
if (isset($_POST['ad_approve'])) $ad_approve = htmlspecialchars(strip_tags(mysql_real_escape_string($_POST['ad_approve'])));
else { $ad_approve = 0; }
Now in the edit.php form I retrieve the data from the database and set the checkbox accordingly . if the approve has the value 1 then it is checked by default . look onto the following code
<input name="ad_approve" type="checkbox" value="1" <?php if($approve==1) echo 'checked="checked"';?> />
in the above code I cannot apply the same logic to catch the value from ad_approve i.e(by checking isset()) because if the value is 1 by default and if I try unchecking the checkbox then automatically the program assume that the value is set because it has been changed from checked to unchecked. now in the edit.php how do I again process the value from it such that if the checkbox is checked hold the value as 1 otherwise 0, ??
to be honest your question does not make a whole lot of sense but I can understand that you wish to check if check boxes are actually set.
firstly you don't need a value attribute on a check box because its the browser that decide what value if any to send via the GP headers.
http://www.w3.org/TR/html401/interact/forms.html
Checkboxes (and radio buttons) are
on/off switches that may be toggled by
the user. A switch is "on" when the
control element's checked attribute is
set. When a form is submitted, only
"on" checkbox controls can become
successful.
So basically if a checkbox is not selected then the entity will not be sent via the headers, there for isset() would be a perfectly usable check.
The way your using real escape is totally wrong, you should never user real escape for html, DATABASE ONLY.
Take this code for example
if(isset($_POST['some_check']))
{
echo $_POST['some_check']; //on
}else
{
echo 'some_check has not been checked';
}
Your code:
if (isset($_POST['ad_approve'])) $ad_approve = htmlspecialchars(strip_tags(mysql_real_escape_string($_POST['ad_approve'])));
else { $ad_approve = 0; }
Can you give me a good excuse why your using htmlspecialchars,strip_tags and mysql_real_escape_string on an entity that can be done like so:
$ad_approve = isset($_POST['ad_approve']) ? true : false;
for issues like this its not that hard to refer to the documentation to get a better understand of what exactly is being sent from the browser.
if you wish to add values to to the checkboxes that you would do this with hidden fields, example follows.
<input type="checkbox" name="check_box" />
<input type="hidden" name="check_box_value" value="01100001" />
And within the php server side.
if(isset($_POST['check_box']))
{
echo $_POST['check_box_value']; //01100001
}else
{
echo 'some_check has not been checked';
}
by adding another html input thats hidden you can hide elements from the user and then use as data holders, the reason why you should use the exact same name but append it with _value is just for best practises.
EDIT
if(isset($_POST['some_check_box']))
{
mysql_query('UPDATE profile SET receive_mail = 1');
}else
{
mysql_query('UPDATE profile SET receive_mail = 0');
}
I had multiple checkbox which is generated using loop. After submitting the form I want to get the names of the selected individual checkbox to store it in database as id. Please help me.. Thanks in advance
Code i used for generating checkbox in loop:
while($arrayRow = mysql_fetch_assoc($rsrcResult))
{
$strA = $arrayRow["area_id"];
$strB = $arrayRow["area_name"];
echo "<div class=\"area_check\"><input type=\"checkbox\" id=\"covarea[] \" />$strB</input></div>";
}
This code I used for getting names for it didnt worked. It only returned state of check box as ON
while (list ($key,$val) = #each ($box))
{
$aid=$val;
echo $aid;
}
If the set of checkboxes is marked up as so
<input type="checkbox" name="food[]" value="Cheese">
<input type="checkbox" name="food[]" value="Ham">
Then any checked values are accessed as an array from $_POST['food']
Obviously with a code example, as #rajasekar points out, it would be easier to recommend an approach
The id for each element is optional, but should/must be unique.
Form elements must have a name attribute, or they will not be submitted (use "covarea[]" for the name for all the chexboxes.
Checkboxes must have a value attribute, or they will be submitted with value "on".
You must ensure that $strA and $strB do not have HTML meta characters or your generated HTML will be invalid.
Your example had a space after the "[]" in the id, btw.
Perhaps like this.
$n = 0;
while($arrayRow = mysql_fetch_assoc($rsrcResult))
{
$strA = $arrayRow["area_id"];
$strB = $arrayRow["area_name"];
$n++;
echo "<div class=\"area_check\"><input type=\"checkbox\" id=\"covarea${n}\" name=\"covarea[]\" value=\"${strA}\"/>$strB</input></div>";
}