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.
Related
Can someone help me to figure out how to replace a defined string value with user input value? I am quite new in PHP programming and could not find an answer. I saw a lot of ways to replace string on the internet by using built-in functions or in arrays, but I could not find out the right answer to my question.
Here is my code:
$text = "Not found";
if ( isset($_GET['user'])) {
$user_input = $_GET['user'];
}
// from here I I tried to replace the value $text to user input, but it does not work.
$raw = TRUE;
$spec_char = "";
if ($raw) {
$raw = htmlentities($text);
echo "<p style='font-style:bold;'> PIN " . $raw . "</p>"; *# displays "Not found"*
} elseif (!$raw == TRUE ) {
$spec_char = htmlspecialchars($user_input);
echo "<p>PIN $spec_char </p>";
}
<form>
<input type="text" name="user" size="40" />
<input type="submit" value="User_val"/>
</form>
I appreciate your answers.
Lets run over your code, line by line.
// Set a default value for $text
$text = "Not found";
// Check if a value has been set...
if (isset($_GET['user'])) {
// But then create a new var with that value.
// Why? Are you going to change it?
$user_input = $_GET['user'];
}
// Define a few vars
$raw = TRUE;
$spec_char = "";
// This next line is useless - Why? Because $raw is always true.
// A better test would be to check for $user_input or do the
// isset() check here instead.
if ($raw) {
// Basic sanity check, but $text is always going to be
// "Not found" - as you have never changed it.
$raw = htmlentities($text);
// render some HTML - but as you said, always going to display
// "Not found"
echo "<p style='font-style:bold;'> PIN " . $raw . "</p>";
} elseif (!$raw == TRUE ) {
// This code is never reached.
$spec_char = htmlspecialchars($user_input);
echo "<p>PIN $spec_char </p>";
}
// I have no idea what this HTML is for really.
// Guessing this is your "input" values.
<form>
<input type="text" name="user" size="40" />
<input type="submit" value="User_val"/>
</form>
Just a guess I think you really wanted to do something more like this:
<?php
// Check if a value has been posted...
if (isset($_POST['user'])) {
// render some HTML
echo '<p style="font-style:bold"> PIN '.htmlspecialchars($_POST['user']).'</p>';
}
?>
<form method="post" action="?">
<input type="text" name="user" size="40" />
<input type="submit" value="User_val"/>
</form>
My code should provide two random numbers and have the user enter their product (multiplication).
If you enter a wrong answer, it tells you to guess again, but keeps the same random numbers until you answer correctly. Answer correctly, and it starts over with a new pair of numbers.
The below code changes the value of the two random numbers even if I entered the wrong number. I would like to keep the values the same until the correct answer is entered.
<?php
$num1=rand(1, 9);
$num2=rand(1, 9);
$num3=$num1*$num2;
$num_to_guess = $num3;
echo $num1."x".$num2."= <br>";
if ($_POST['guess'] == $num_to_guess)
{ // matches!
$message = "Well done!";
}
elseif ($_POST['guess'] > $num_to_guess)
{
$message = $_POST['guess']." is too big! Try a smaller number.";
}
elseif ($_POST['guess'] < $num_to_guess)
{
$message = $_POST['guess']." is too small! Try a larger number.";
}
else
{ // some other condition
$message = "I am terribly confused.";
}
?>
<!DOCTYPE html>
<html>
<body>
<h2><?php echo $message; ?></h2>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="answer" value="<?php echo $answer;?>">
<input type="hidden" name="expression" value="<?php echo $expression;?>">
What is the value of the following multiplication expression: <br><br>
<?php echo $expression; ?> <input type="text" name="guess"><br>
<input type="submit" value="Check">
</form>
</body>
</html>
In order to keep the same numbers, you have to store them on the page and then check them when the form is submitted using php. You must also set the random number if the form was never submitted. In your case, you were always changing num1 and num2. I tried to leave as much of your original code intact, but it still needs some work to simplify it.
First I added 2 more hidden field in the html called num1 and num2
Second, I set $num1 and $num2 to the value that was submitted from the form.
After following the rest of the logic, I make sure that $num1 and $num2 are reset if the answer is correct of it the form was never submitted.
You can see the comments in the code below.
Additionally, if you were going to use this in a production environment, you would want to validate the values being passed in from the form so that malicious users don't take advantage of your code. :)
<?php
// Setting $num1 and $num2 to what was posted previously and performing the math on it.
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$num_to_guess = $num1*$num2;
// Check for the correct answer
if ($_POST && $_POST['guess'] == $num_to_guess)
{
// matches!
$message = "Well done!";
$num1=rand(1, 9);
$num2=rand(1, 9);
}
// Give the user a hint that the number is too big
elseif ($_POST['guess'] > $num_to_guess)
{
$message = $_POST['guess']." is too big! Try a smaller number.";
}
// Give the user a hint that the number is too small
elseif ($_POST['guess'] < $num_to_guess)
{
$message = $_POST['guess']." is too small! Try a larger number.";
}
// If the form wasn't submitted i.e. no POST or something else went wrong
else
{
// Only display this message if the form was submitted, but there were no expected values
if ($_POST)
{
// some other condition and only if something was posted
$message = "I am terribly confused.";
}
// set num1 and num2 if there wasn't anything posted
$num1=rand(1, 9);
$num2=rand(1, 9);
}
// Show the problem
echo $num1."x".$num2."= <br>";
?>
<!DOCTYPE html>
<html>
<body>
<h2><?php echo $message; ?></h2>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="num1" value="<?= $num1 ?>" />
<input type="hidden" name="num2" value="<?= $num2 ?>" />
<input type="hidden" name="answer" value="<?php echo $num3;?>">
<input type="hidden" name="expression" value="<?php echo $expression;?>">
What is the value of the following multiplication expression: <br><br>
<input type="text" name="guess"><br>
<input type="submit" value="Check">
</form>
</body>
</html>
When you load the page for the first time, you have (i.e.) “2*3” as question. $_POST is not defined, so if ($_POST['guess']... will produce a undefined index warning. Then you echo $message, but where you define $message? $_POST['guess'] is undefined, so is evaluated as 0, $num_to_guess is 6 (=2*3), so $message is set to " is too small! Try a larger number.", even if the user has not input anything. The hidden answer is set to $answer, but this variable is not defined so it is set to nothing (or to “Notice: Undefined variable: answer”, if you activate error reporting). Same issue for expression input and for echo $expression.
Try something like this:
$newQuestion = True; // This variable to check if a new multiplication is required
$message = '';
/* $_POST['guess'] check only if form is submitted: */
if( isset( $_POST['guess'] ) )
{
/* Comparison with answer, not with new result: */
if( $_POST['guess'] == $_POST['answer'] )
{
$message = "Well done!";
}
else
{
/* If result if wrong, no new question needed, so we propose same question: */
$newQuestion = False;
$answer = $_POST['answer'];
$expression = $_POST['expression'];
if( $_POST['guess'] > $_POST['answer'] )
{
$message = "{$_POST['guess']} is too big! Try a smaller number.";
}
else
{
$message = "{$_POST['guess']} is too small! Try a larger number.";
}
}
}
/* New question is generated only on first page load or if previous answer is ok: */
if( $newQuestion )
{
$num1 = rand( 1, 9 );
$num2 = rand( 1, 9 );
$answer = $num1*$num2;
$expression = "$num1 x $num2";
if( $message ) $message .= "<br>Try a new one:";
else $message = "Try:";
}
?>
<!DOCTYPE html>
(... Your HTML Here ...)
This might also be fun to learn. This is a session. Lets you store something temporarily. It is a little dirty. But fun to learn from.
http://www.w3schools.com/php/php_sessions.asp
<?php
session_start(); // Starts the Session.
function Save() { // Function to save $num1 and $num2 in a Session.
$_SESSION['num1'] = rand(1, 9);
$_SESSION['num2'] = rand(1, 9);
$_SESSION['num_to_guess'] = $_SESSION['num1']*$_SESSION['num2'];;
$Som = 'Guess the number: ' . $_SESSION['num1'] .'*' .$_SESSION['num2'];
}
// If there is no session set
if (!isset($_SESSION['num_to_guess'])) {
Save();
$message = "";
}
if (isset($_POST['guess'])) {
// Check for the correct answer
if ($_POST['guess'] == $_SESSION['num_to_guess']) {
$message = "Well done!";
session_destroy(); // Destroys the Session.
Save(); // Set new Sessions.
}
// Give the user a hint that the number is too big
elseif ($_POST['guess'] > $_SESSION['num_to_guess']) {
$message = $_POST['guess']." is too big! Try a smaller number.";
$Som = 'Guess the number: ' . $_SESSION['num1'] .'*' .$_SESSION['num2'];
}
// Give the user a hint that the number is too small
elseif ($_POST['guess'] < $_SESSION['num_to_guess']) {
$message = $_POST['guess']." is too small! Try a larger number.";
$Som = 'Guess the number: ' . $_SESSION['num1'] .'*' .$_SESSION['num2'];
}
// some other condition
else {
$message = "I am terribly confused.";
}
}
?>
<html>
<body>
<h2><?php echo $Som . '<br>'; ?>
<?php echo $message; ?></h2>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="guess"><br>
<input type="submit" value="Check">
</form>
</body>
</html>
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'];
<?
//LUHN ALGORITHM PHP CONVERSION
// CREDIT CARD NUMBER CHECKER BY JACK BELLAMY - JACKBELLAMY.CO.UK
//----------- RETREIVE THE STRING FROM THE FORM POST -------------//
$var = $_POST['cardnumber'];
//----------- SPLIT THE 16 CHARACTOR STRING INTO INDIVIDUAL CHARACTERS AND ASSIGN TO INDIVIDUAL VARIABLES ---------------//
$n0 = $var[0];
$n1 = $var[1];
$n2 = $var[2];
$n3 = $var[3];
$n4 = $var[4];
$n5 = $var[5];
$n6 = $var[6];
$n7 = $var[7];
$n8 = $var[8];
$n9 = $var[9];
$n10 = $var[10];
$n11 = $var[11];
$n12 = $var[12];
$n13 = $var[13];
$n14 = $var[14];
$n15 = $var[15];
// ---------------------CHECKING THE CARDNUMBER FORM POST SUBMITS ALL VALUES PROPERLY
/*
echo $n0;
echo $n1;
echo $n2;
echo $n3;
echo $n4;
echo $n5;
echo $n6;
echo $n7;
echo $n8;
echo $n9;
echo $n10;
echo $n11;
echo $n12;
echo $n13;
echo $n14;
echo $n15;
*/
//-------ASSIGNING THE NEW VARIABLE VALUES ------------//
$n14_new = ($n14*2);
$n12_new = ($n12*2);
$n10_new = ($n10*2);
$n8_new = ($n8*2);
$n6_new = ($n6*2);
$n4_new = ($n4*2);
$n2_new = ($n2*2);
$n0_new = ($n0*2);
//!-----!------!//
//------------------------TESTING WITH THE NEW VARAIBLE *2
/*
echo $n0_new;
echo $n1;
echo $n2_new;
echo $n3;
echo $n4_new;
echo $n5;
echo $n6_new;
echo $n7;
echo $n8_new;
echo $n9;
echo $n10_new;
echo $n11;
echo $n12_new;
echo $n13;
echo $n14_new;
echo $n15;
*/
//--------- THE MATHS FOR THE COMPLETE SUM ------------ //
$isitlegit = ($n0_new+$n1+$n2_new+$n3+$n4_new+$n5+$n6_new+$n7+$n8_new+$n9+$n10_new+$n11+$n12_new+$n13+$n14_new+$n15);
//!----MATHS-----!//
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="veri-styles.css"
</head>
<body>
<div class="container">
<div class="main-wrapper">
<div id ="verification-wrapper">
<form action="" method="post" enctype="application/x-www-form-urlencoded">
<div id="input-holder">
<input name="cardnumber" type="text" class="input-style" placeholder=""> </input>
<button class="button-style">Verify my card</button>
</div>
</form>
<div class="result-class">
<?php
if(isset($isitlegit) && ($isitlegit % 5 == 0)) { // it's good
$new = "<img src='correct.jpg' />";
} elseif(isset($isitlegit) && ($isitlegit % 5 != 0)) { // it's bad
$new = "<img src='incorrect.jpg' />";
} elseif(!isset($isitlegit)) { // make sure this is not set
$new = "<img src='card-number-required.jpg' />";
}
echo $new;
?>
</div>
</div>
</div>
</body>
</html>
You have three states you need to account for, 'open', 'correct', and 'incorrect' To do that you start with an 'open' state.
$new = "<img src='please_enter your card number.jpg' />";
echo $new;
You would use that in the first condition of your test -
if(isset($var) && ($isitlegit % 5 == 0)) { // it's good
$new = "<img src='correct.jpg' />";
} elseif(isset($var) && ($isitlegit % 5 != 0)) { // it's bad
$new = "<img src='incorrect.jpg' />";
} else { // the default view
$new = "<img src='please_enter your card number.jpg' />";
}
echo $new;
Once submitted you can only have one of two states, never to return to the default.
In addition you have left your stylesheet declaration un-closed. Please change it to this -
<link rel="stylesheet" type="text/css" href="veri-styles.css" />
if(false===$submitted){
echo "Please type your card details here";
} else {
if($isitlegit % 5 == 0) {
$new = "<img src='correct.jpg' />";
echo $new;
}
else {
$new = "<img src='incorrect.jpg' />";
echo $new;
}
}
The best way I can think of to achieve this is with AJAX. Create a div on your page where your initial message is displayed, and then use an AJAX call to submit the form data to a script you'll use to validate it, and within that script, echo either a "Success! Your card has been verified" or a "Unable to validate your card" message. Then have your AJAX function change the .innerHTML of the div to the responseText element. You can see this answer for a good starting point, as well as a note about using the jQuery library to simplify your AJAX implementation.
Edit: In response to another user's downvote, here's some code.
First, let's give your HTML form a call to an AJAX object we'll create. So change your HTML form code to this:
<form onSubmit="return process()">
process() is a javaScript function we're going to set up later with the AJAX call. You already have a div established where you want this data to appear, but we need to give it an id, so change:
<div class="result-class">
please enter your card number<img src='correct.jpg' />
</div>
to this:
<div class="result-class" id="result">
Please enter your card number.
</div>
And also assign an id to your text input:
<input name="cardnumber" type="text" class="input-style" placeholder="" id="cardnumber"> </input>
Now we'll create the javaScript function. (This is easier with jQuery, but I wrote it in plain javaScript so you won't need the dependancy if you're not familiar with how to use jQuery.
function process(){
var xmlhttp = new XMLHttpRequest();
var cardnumber = document.getElementById("cardnumber").value;
var result = document.getElementById("result");
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
result.innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","validate.php?cardnumber=" + cardnumber,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
return false;
}
Now, use whatever php script you were going to use to validate the cc# and save it as a separate script called validate.php Use $_GET['cardnumber'] variable to fetch the cardnumber data sent from the form, run it through whatever validation process you are using. Use an if statement to create the responseText element for our AJAX function. You might have your script set some variable to boolean true or false to check this. I'll use $validated here.
if($validated){
echo 'Your card has been verified!';
} else {
echo 'Unable to validate your card.';
}
The AJAX function will change the text inside the "result" div to whatever text is echoed by your validate.php script.
This should get you on the right track, barring any syntax errors, I just wrote this all off the cuff.
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!