I want to post conditional operator from Form Input. And in IF condition use the posted operator. Unable to do so any logic to gt it done.
<form action="" method="post" accept-charset="utf-8">
<input name="postvalue" size="5" maxlength="7" value=">=5">
<p><input type="submit" value="Go"></p>
</form>
<?php
if(10 $_POST["postvalue"]) {
echo "Its greater than 5";
} else {
echo "Its less than 5";
}
?>
You are probably looking for something like this:
<form action="" method="post" accept-charset="utf-8">
<input name="term" size="5" maxlength="7" value=">=5">
<p><input type="submit" value="Go"></p>
</form>
<?php
// separate operator and operand from the posted value
preg_match('/^([=<>!]+)([0-9]+)$/', $_POST['term'], $tokens);
$operator = $tokens[1];
$operand = $tokens[2];
// create an evaluation function
$check = create_function('$value', '
$operand = '.$operand.';
switch("'.$operator.'") {
case "==": return ($value==$operand);
case "!=": return ($value!=$operand);
case "<": return ($value<$operand);
case "<=": return ($value==$operand);
case ">": return ($value>$operand);
case ">=": return ($value>=$operand);
default: throw new Exception("invalid operator");
}');
// apply the evaluation function to some value
try {
if ($check(10)) {
echo "10 is greater than 5";
} else {
echo "10 is less than 5";
}
} catch (Exception $e) {
echo sprintf('Exception: %s', $e->getMessage());
}
?>
Obviously error detection has to be added and the like...
Anyway this is a pretty "strange" architecture... Consider other approaches, since this approach is somewhat prone to failures. Instead you should post operand and operator in separate input fields (post fields) to simplify evaluation and make things more robust. The operator probably should be offered as a select input, the operand as a number spinner...
Related
**hi here is the code please answer my question. I'm trying to echo condition by given input but results are three times I want single result condition by given input **
<?php
$arrayName = array('bravo', 'alpha', 'jhony');
foreach ($arrayName as $key) {
if (isset($_REQUEST['num1']) && $_REQUEST['num1'] == $key) {
echo "yes". $_REQUEST['num1']. "Available";
} else {
echo "Sorry!".$_REQUEST['num1']." is not available";
}
}
?>
<form action="" method="get" accept-charset="utf-8">
<input type="text" name="num1">
<button type="submit">submit</button></form>
Rather than loop through your white list, use in_array:
$arrayName = array('bravo','alpha','jhony' );
if(isset($_REQUEST['num1']) && in_array($_REQUEST['num1'], $key)){
echo "yes". $_REQUEST['num1']. "Available";
}
else{
echo "Sorry!".$_REQUEST['num1']." is not available";
}
I'm trying to use the switch statements but it's not working. My problem is for example i input LazyBoy in the textbox, that should echo LazyBoy else echo another string.
<?php
$classmap = $_POST['classmap'];
switch ($classmap) {
case "LazyBoy":
echo "You're Lazy!";
break;
case "GrayHounds":
echo "You're Gray!";
break;
}
?>
Here is the form -
<form action="checkout.php" method="post" >
<input type="hidden" name ="classmap" value="<?php include('db.php');
$origin = $_POST['origin'];
$class = $_POST['class'];
$daten = $_POST['daten'];
$result = mysql_query("SELECT * FROM route WHERE route LIKE '%$origin%' AND type LIKE '%$class%' AND date LIKE '%$daten%' ");
while($row = mysql_fetch_array($result))
{
echo $row['type'];
} ?>">
</form>
You just need to check if the post variable is set and/or add a default case :
if(isset($_POST['classmap'])) {
$classmap = $_POST['classmap'];
switch ($classmap) {
case "LazyBoy":
echo "Your Lazy!";
break;
case "GrayHounds":
echo "Your Gray!";
break;
default:
echo "Something";
break;
}
}
else {
echo "Something";
}
Make sure you post to the right script.
Try to put default statement to debug.
$classmap = $_POST['classmap'];
switch ($classmap) {
case "LazyBoy":
echo "You're Lazy!";
break;
case "GrayHounds":
echo "You're Gray!";
break;
default:
echo "does not match with previous cases";
}
First you have to post values to define the classmap index.
<form method="post">
<input type="text" name="classmap" value="LazyBoy"/>
<input type="submit" value="submit"/>
</form>
<?php
$classmap = (isset($_POST['classmap']) ? $_POST['classmap'] : null);
switch ($classmap) {
case "LazyBoy":
echo "You're Lazy!";
break;
case "GrayHounds":
echo "You're Gray!";
break;
}
?>
Your Code is correct.
I guess there is a Problem with the $_POST.
Try to verify it.
$classmap = "LazyBoy";
So, I have this code
<?php
if(!isset($_POST["step1_submit"]))
{
echo "Fill step1!";
step1();
}
function step1()
{
if(isset($_POST["step1_submit"]))
{
step2();
}
else
{
echo '<form action="" method="post">STEP 1: <input name="step1_input"/><input name="step1_submit" type="submit" value=">>STEP 2>>"/></form>';
}
}
function step2()
{
echo "reached step 2";
if(isset($_POST["step2_submit"]))
{
echo '<br/>'.$_POST["step2_input"];
step3();
}
else
{
echo '<form method="post">STEP 2: <input name="step2_input"/><input name="step2_submit" type="submit" value=">>STEP 3>>"/></form>';
}
}
function step3()
{
echo '<strong>WELL DONE</strong>';
}
?>
It shows the input for step1, but never gets to show step2. In my opinion, it gets stuck on calling the function step2, because while doing it, the isset($_POST(step1_submit)) changes it value to NULL.
How can I manage to make this code work? It should be like: filling step 1 input >> getting to fill step 2 input >> submit step 2 >> get to see the 'WELL DONE' echo.
Basically the conditional statement on top needs an else branch:
if(!isset($_POST["step1_submit"]))
{
echo "Fill step1!";
step1();
} else {
step2();
}
...
However, if you have more steps it should look like this:
switch(TRUE) {
case isset('step1_submit') :
step2();
break;
case isset('step2_submit') :
step3();
break;
...
default:
echo "Fill step1!";
step1();
}
Then change your functions to:
function step1()
{
echo '<form action="" method="post">STEP 1: <input name="step1_input"/><input name="step1_submit" type="submit" value=">>STEP 2>>"/></form>';
}
function step2()
{
echo '<form action="" method="post">STEP 2: <input name="step2_input"/><input name="step2_submit" type="submit" value=">>STEP 3>>"/></form>';
}
...
The if conditionals aren't required there.
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 have a form with 3 checkboxes, and my idea is run some commands if they are selected and do something else if they are not selected.
for($i=1; $i<=3; $i++)
{
if ($_POST['option'.$i])
{
echo "123";
}
if (!$_POST['option'.$i])
{
echo "456";
}
}
But if they are not selected the commands are not executed.. The if statement is correct?
No, what you should be doing is checking them like this:
if (isset($_POST['option'.$i]))
Otherwise, you are just trying to evaluate the boolean form of whatever is in that $_POST element. Why is this bad? Suppose the value of that field were 0. Even though the checkbox was checked, your code wouldn't run.
Documentation for isset()
Sure, that will work just fine.
If you want to slightly de-uglify your code, you can do it this way:
<input type="checkbox" name="options[option_name]" value="1" />
<input type="checkbox" name="options[second_option_name]" value="1" />
if(isset($_POST['options']) && is_array($_POST['options']) {
foreach($_POST['options'] as $option_name => $ignore_this) {
switch($option_name) {
case 'option_name':
// do something
break;
case 'second_option_name':
// do something else
break;
}
}
}
You can use an if ... else:
if ($_POST['option'.$i])
{
echo "123";
}
else
{
echo "456";
}
to avoid checking the same condition twice.