Need som serious help!
<?php
$php1 = !isset($_GET['php1']);
$php2 = !isset($_GET['php2']);
$php3 = !isset($_GET['php3']);
$php4 = !isset($_GET['php4']);
$php5 = !isset($_GET['php5']);
if ($php1 == 'one' && $php2 == 'two' && $php5 == 'five') {
echo "<h2>R</h2>WRONG";
} else {
echo "<h2>R</h2>CORRECT";
}
?>
HTML
<form action="One.php" method="get">
<input type="checkbox" name="php1" value="one"> q1<br>
<input type="checkbox" name="php2" value="two"> q1<br>
<input type="checkbox" name="php3" value="three"> q1<br>
<input type="checkbox" name="php4" value="four"> q1<br>
<input type="checkbox" name="php5" value="five"> q1<br>
<br>
<input type="submit" value="Send!">
</form>
If all checkboxes are empty, there will be a message saying that. How do I do it?
If I dont check any boxes, it tells me the answers are correct. That's wrong.
<?php
If(isset($_GET['php1'])){
$php1 = 1;
}else{
$php1 = 0;
}
If(isset($_GET['php2'])){
$php2 = 1;
}else{
$php2 = 0;
}
If(isset($_GET['php3'])){
$php3 = 1;
}else{
$php3 = 0;
}
If(isset($_GET['php4'])){
$php4 = 1;
}else{
$php4 = 0;
}
If(isset($_GET['php5'])){
$php5 = 1;
}else{
$php5 = 0;
}
if ($php1 && $php2 && $php5) {
echo "<h2>Resultat</h2>Du svarade rätt på frågan";
} else {
echo "<h2>Resultat</h2>Du svarade fel på frågan";
}
Try this.
Each php variable will have the value of 1 or 0 (true/false). Thus the if only needs to check it if it is or not.
You have to remember that UN-CHECKED Checkboxes are not even sent to the PHP script $_POST/$_GET by the browser.
So there existance is normally all you need to know.
First you must check that they were passed to the script and then check its value, otherwise you will receive undefined index errors for each checkbox that was not checked by the user
if (isset($_GET['php1']) && $_GET['php1'] != '' ) {
Although as the checkbox called php1 can only be set to the value you give it, its value can be assumed and all you need to do is
if (isset($_GET['php1']) ) {
// php1 was checked
Also isset() will test more than one variable exists using an AND. So you could write your code as
if ( isset($_GET['php1'], $_GET['php2'], $_GET['php5']) ) {
echo "<h2>Resultat</h2>Du svarade rätt på frågan";
} else {
echo "<h2>Resultat</h2>Du svarade fel på frågan";
}
$php1 = !isset($_GET['php1']);
This means $php1 is either true or false. If you want the value of php1 get parameter then remove isset cover, just
$_GET['php1'];
isset is used to check whether the variable exist or not after that use $_GET['php1'];
Related
I have inserted a checkbox in my form.
My code:
<input type="checkbox" id="checkbox" name="checkbox" value="1"/>
if($checkbox = ($_POST['checkbox']) == '1')
{
$checkbox = "si";
}
else
{
$checkbox = "no";
}
I would like that if the checkbox is checked i receive "yes" otherwise "no".
Thanks.
You've written wrong if condition here, You cannot use assignment in conditions.
Also there is no need to assign value to any variable in checking condition, You can directly use $_POST['checkbox']. Like this,
if($_POST['checkbox'] == '1') {
$checkbox = "si";
} else {
$checkbox = "no";
}
Update:
A better option is to use isset() which determine if a variable is set and is not NULL. Like this,
if(isset($_POST['checkbox'])) {
$checkbox = "si";
} else {
$checkbox = "no";
}
Program will go in if condition only when user has checked the checkbox. In above case value attribute for <input> is not required. So your HTML will look something like this,
<input type="checkbox" id="checkbox" name="checkbox"/>
$request['checkbox_name'] = $request['checkbox_name'] == null ? 'N' : 'Y'; //for default value
When I check the checkbox there is no errors, but when I didn't check the checkbox it gives me errors.
<?php
if(isset($_REQUEST['btn']))
{
$remmber = $_REQUEST['active'];
if($remmber == "on")
{
echo "Checked";
}
else {$remmber = "";}
}
?>
<html>
<form name= "frm" action = "test.php" method = "post" >
<p>Username
<input type = "text" name = "name" value = "" />
</p>
<p>Password
<input type = "text" name = "password" value = "" />
</p>
<p>
<td colspan = "2"><input type = "checkbox" name = "active" value = "active" />Keep Me Loged In
</p>
<p><input type = "submit" name = "btn" value = "Login" />
</p>
</form>
</html>
For checkboxes if they are not checked then they are not posted. So check if it is present in the posted data then set on, else set blank to the variable. Try with -
if(isset($_REQUEST['btn']))
{
$remmber = !empty($_REQUEST['active']) ? 'on' : '';
if($remmber == "on")
{
echo "Checked";
}
else
$remmber = "";
}
if($remmber == "on") yet you're using and specifying a value value = "active"
"on" is the default value for a checkbox if a value is not specified.
Therefore, you need to adjust it to read as
if($remmber == "active")
Edit: (an explanation)
The reason why you're getting an undefined index, is that once you hit the submit submit and do not tick the checkbox, it will produce that notice.
Modify your code to read as and check if the checkbox value is set.
if(isset($_REQUEST['btn']))
{
if(isset($_REQUEST['active'])){
$remmber = $_REQUEST['active'];
if($remmber == "active")
{
echo "Checked";
}
else {$remmber = "";}
} // closing brace for if(isset($_REQUEST['active']))
}
Additional edit, to show the user that the checkbox isn't set:
if(isset($_REQUEST['btn']))
{
if(isset($_REQUEST['active'])){
$remmber = $_REQUEST['active'];
if($remmber == "active")
{
echo "Checked";
}
else {$remmber = "";}
} // closing brace for if(isset($_REQUEST['active']))
else{ echo "The checkbox was not ticked.";
}
}
Footnotes:
You should also use a conditional !empty() for your inputs.
You're only checking if the submit and checkbox are set.
After noticing a comment you left in another answer:
#Barmar i am just using this for login page , where i am using a checkbox to remember username and password. – Akshat Dhiman
Please read the following Q&A on Stack:
Remember me Cookie best practice?
It also contains valuable information regarding passwords.
I hope you are using modern-day hashing methods also, such as password_hash() as well as prepared statements.
you can use simply isset
if(isset($_REQUEST['btn']))
{
$remmber = isset($_REQUEST['active']) ? $_REQUEST['active'] : '';
if($remmber == "on")
{
echo "Checked";
}
else {$remmber = "";}
}
In my form I am trying to get the radio checked value to be passed on to the next page (which is an FPDF page)
I have 4 options: Annual Leave, Sick Leave, Business Leave, & also others with a textfield.
However I have tried a lot of 'if' as well as 'switch cases'
I am getting either only the element with value '1'
or else 'Undefined index: rad in D:\xampp\htdocs\Application\generate_report.php on line 13'
some where I am wrong, can anyone help me please. My code below.
html form:
<form id="formmain" method="post" action="generate_report.php" onsubmit="return_validate()">
<script type="text/javascript">
function selectRadio(n){
document.forms["form4"]["r1"][n].checked=true
}
</script>
<table width="689">
<tr>
<td width="500d">
<input type="radio" name="rad" value="0" />
<label>Business Trip</label>
<input type="radio" name="rad" value="1"/><label>Annual Leave</label>
<input type="radio" name="rad" value="2"/><label>Sick Leave</label>
<input type="radio" name="rad" value="3"/><label>Others</label> <input type="text" name="others" size="25" onclick="selectRadio(3)" />
</td>
</tr>
</table>
//....
//below submit button is end of the html page:
<input type="submit" name="submit" value="send" />
</form>
Generate PDF form:
$radio = $_POST['rad']; // I am storing variable
if($radio = 0) {
$type = 'Business Leave';
}elseif ($radio = 1) {
$type = 'Annual Leave';
}elseif ($radio = 2) {
$type = 'Sick Leave';
} else { $type = $_POST['others']; }
//echo
$pdf->Cell(98,10, 'Reason | ' .$type , 1, 0, 'C', $fill);
if($radio = 0)
and
elseif ($radio = 1)
and all the other elseifs have to be == 1, with two '='!
A further explanation on the OP. If you do not use == then you are setting the value, not checking it. Furthermore, there are levels of checking. Using the double equals (==) is effectively stating "is equal to" whereas using triple equals (===) is like stating "is absolutely equal to". Generally the == operator will do everything you need but sometimes when working with data types or specific values you might need ===. This is mostly FYI as the OP has an actionable solution.
You should always check if inputs are checked or any value inserted. If there's no value, then it throws an undefined index error. Also, you should replace =s to == in your if clauses. So:
PHP:
$radio = $_POST['rad']; // I am storing variable
if (isset($radio)) { // checks if radio is set
if($radio == 0) {
$type = 'Business Leave';
}elseif ($radio == 1) {
$type = 'Annual Leave';
}elseif ($radio == 2) {
$type = 'Sick Leave';
} else {
if (isset($_POST['others'])) { // cheks if input text is set
$type = $_POST['others'];
}
else {
echo 'Error';
}
}
//echo
$pdf->Cell(98,10, 'Reason | ' .$type , 1, 0, 'C', $fill);
}
else {
echo 'Error';
}
Now it should work.
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!
I am new to the world of PHP and have put together a form that multiplies an entered value. However when I attempt to validate if a person has not entered any values to return an error message, it does display the message. My code below. Appreciate if you could also suggest improvements.
<?php
$counter = 0;
if(isset($_POST["submit"])) {
$start = $_POST["start"];
$end = $_POST["end"];
$multiply = $_POST["multiplication"];
// if($_POST["start"] == "" && $_POST["end"] == "" && $_POST["multiplication"] == "") {
// print "Please enter some values";
// }
if(!isset($_POST["start"], $_POST["end"], $_POST["multiplication"])) {
print "Please enter some values";
}
// for($start;$start<$end;$start++) {
// $counter = $counter +1;
// $multiplication = $counter * $multiply;
// print "$counter <br />";
// print "$counter multiplied by $multiply = $multiplication <br />";
// }
}
?>
<html>
<head>
<title>Sample Multiplication</title>
</head>
<body>
<form name="multiply" method="post" action="multiplication_sample.php">
<input type="text" name="start" value="<?php if(isset($_POST["start"])) { print $start; } ?>">
<input type="text" name="end" value="<?php if(isset($_POST["end"])) { print $end; } ?>">
<input type="text" name="multiplication" value="<?php if(isset($_POST["multiplication"])) { print $multiply; } ?>">
<input type="submit" name="submit" value="submit">
</form>
<?php
if(isset($_POST["submit"])) {
for($start;$start<$end;$start++) {
$counter = $counter + 1;
$multiplication = $counter * $multiply;
print "$counter multiplied by $multiply = $multiplication <br />";
}
}
?>
</body>
</html>
I think that isset will make sure a variable is not NULL, however, "blank" is not the same as null. If you submit a form with blank values, the variable is still being set, it is just empty.
When the form is submitted, the content of the input fields is sent to the server.
If those input fields are empty, the server gets an empty string for each input -- but it gets something ; so, the $_POST["start"], $_POST["end"], $_POST["multiplication"] items are set -- even if they only contain empty strings.
You could check :
If the fields contain an empty string : if ($_POST["start"] === '')
Or if if contains only blank spaces : if (trim($_POST["start"]) === '')
Or if they are empty : if (empty($_POST["start"]))
If the fields aren't defined your code will print your message in the html before the <html> tag appears. Most browsers won't display it or display it in an unexpected place.
You should move the message display somewhere in the html where the user could see it.
And as other pointed out, except on the first call of the page the fields will have an empty value but still exists (and so isset will return TRUE)
I hope, I understand you right. It is
if(!isset($_POST["start"], $_POST["end"], $_POST["multiplication"])) {
print "Please enter some values";
}
that works not as expected? It seems, that you assume an empty string means, that nothing is set, what is not true.
$x = "";
isset($x); // true
Use empty() or just $_POST['start'] == '' instead.