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.
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
Ok so I have a form with 1 input and a submit button. Now I am using an if/else statement to make three acceptable answers for that input. Yes, No, or anything else. This if/else is working the thing is the code is kicking out the else function as soon as the page is loaded. I would like there to be nothing there until the user inputs then it would show one of three answers.
Welcome to your Adventure! You awake to the sound of rats scurrying around your dank, dark cell. It takes a minute for your eyes to adjust to your surroundings. In the corner of the room you see what looks like a rusty key.
<br/>
Do you want to pick up the key?<br/>
<?php
//These are the project's variables.
$text2 = 'You take the key and the crumby loaf of bread.<br/>';
$text3 = 'You decide to waste away in misery!<br/>';
$text4 = 'I didnt understand your answer. Please try again.<br/>';
$a = 'yes';
$b = 'no';
// If / Else operators.
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
}
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
?>
<form action="phpgametest.php" method="post">
<input type="text" name="name" /><br>
<input type="submit" name="senddata" /><br>
</form>
You just need to call the code only when the POST value is set. This way it will only execute the code when the form was submitted (aka $_POST['senddata'] is set):
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
}
Just put the validation in the first if statement like this:
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a) {
echo ($text2);
} elseif ($usertypes == $b) {
echo ($text3);
} else {
echo ($text4);
}
}
When you load your page the browser is making a GET request, when you submit your form the browser is making a POST request. You can check what request is made using:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Your form was submitted
}
Put this around your form processing code in order to keep it from being executed on GET request.
I need a simple php function to mimic an Ajax form submission - basically in the form there is a radio button "ajax" and it is either set to yes or no. I just need to mimic successful/failing ajax calls...
HTML
<label for="">Ajax Success*<input type="radio" name="ajax" id="yes" value="yes" checked>Yes<input type="radio" name="ajax" id="no" value="no">No</label>
PHP
<?php
$ajax = $_POST["ajax"];
if(isset($_POST['ajax'] == "yes")) {
echo "success";
} else {
echo "failure";
}
?>
if I remove the isset, I get an 'undefined index' error, if I put it in I get a syntax error but it looks correct to me...
I just need to send back an echo depending on what option is selected for the input 'ajax'
thx
isset($_POST['ajax'] == "yes") doesn't make sense. You want to check if it's set, and then check if its value is equal to "yes":
if(isset($_POST['ajax']) && $_POST['ajax'] == "yes") {
echo "success";
} else {
echo "failure";
}
As your code does, I'll say you use your defined variable like in this example:
<?php
$ajax = $_POST["ajax"];
if($ajax == "yes") {
echo "success";
} else {
echo "failure";
}
?>
Because if the variable has the value "yes" it'll be ok and undefined or other value will end in "failure".
Can i write some code to execute while my check box is checked in my php code..
my declaration of check box is...
<input id="checkbox" name="click" type="checkbox" onclick="check(this)"/>
i thought to perform a function called check() while clicking the check box..
<script type="text/javascript">
function check(cb)
{
if($("input[type=checkbox]:checked"")
{
//my functionality and operations
}
}
But its not working, how can i perform the onclick event in the Checkbox's action..
First of all, there's a mistake. It should be .is(":checked").
function check(cb)
{
if($(cb).is(":checked"))
{
//my functionality and operations
}
}
And the HTML should be:
<input type="checkbox" onclick="check(this);" />
Or, if you wanna invoke a PHP Function after clicking on Checkbox, you need to write an AJAX code. If this is the case, in your if condition, and checked condition, you can call a PHP file, that calls only this function.
function check(cb)
{
if($(cb).is(":checked"))
{
$.getScript("clickCheckbox.php");
}
}
And you can write JavaScript plus PHP in the clickCheckbox.php file, say something like this:
clickCheckbox.php
<?php
header("Content-type: text/javascript");
unlink("delete.png");
echo 'alert("Deleted!");';
?>
Once you click on the checkbox, and if the state is checked, it gives out an AJAX call to this PHP file, where you are deleting a file delete.png and in the echo statement, you are outputting a JavaScript alert, so that you will get an alert message saying Deleted!.
$('#myform :checkbox').click(function() {
var $this = $(this);
// $this will contain a reference to the checkbox
if ($this.is(':checked')) {
// the checkbox was checked
} else {
// the checkbox was unchecked
}
});
Where your form has id myform
use
if ($('#checkbox').is(':checked'))
or inside an event
$('#checkbox').click(function(){
if ($(this).is(':checked')){
//your routine here if checked
}else{
//routine here if not checked
}
});
You can put like this:
Include the column checked in your table with default value NO.
Then after your SELECT statement show the array.
page1.php
<input type=checkbox value="<?php $row['checked']?>" onclick="location.href = 'update.php?id=<?php echo $row['id']; ?>&checked=<?php if ($row['checked'] == 'YES') { ?>NO<?php } else {?>YES<?php } ?>';" <?php if ($row['checked'] == 'YES') { ?> checked <?php } ?>>
update.php
<?php include('server.php'); ?>
<?php
$id = $_GET['id'];
$checked = $_GET['checked'];
if(isset($_GET['id']))
{
$sql = "UPDATE table SET
checked = '$checked'
WHERE `id` = '$id' ";
if ($conn->query($sql) === TRUE)
{
}
else
{
echo "Error updating record: " . $conn->error;
}
header('location: page1.php');
}
?>
Try this one
<input id="checkbox" name="click" type="checkbox" onclick="check()"/>
//in js
if( $('input[name=checkbox]').is(':checked') ){
// your code
}
I have a function that sets and unset's a $_SESSION variable depending on what was submitted from the form in my main page.
function if statement:
$_SESSION['search'] = true;
if($_POST['searchtv']){
$_SESSION['searchtv'] = true;
} else {
unset($_SESSION['searchtv']);
}
if($_POST['searchmovie']){
$_SESSION['searchmovie'] = true;
} else {
unset($_SESSION['searchmovie']);
}
The searchtv and searchmovie $_POST variables are set through the below checkboxes:
<input type="checkbox" name="searchmovie" value="movie" <? echo isset($_SESSION['searchmovie']) ? 'checked' : ''; ?>"/>
However the checked value always seems to be false and displays '' so no "checked" is set to display the tick in the box.
I do know that the $_SESSION variable is being set correctly however because in the same file i have another IF statement (below) that works 100%.
if(isset($_SESSION['searchtv'])){
$database->searchTV($_GET['show'], $session->uid);
}
if(isset($_SESSION['searchmovie'])){
$database->searchMovies($_GET['show'], $session->uid);
}
if(!isset($_SESSION['searchtv']) && !isset($_SESSION['searchmovie'])){
$database->searchTV($_GET['show'], $session->uid);
$database->searchMovies($_GET['show'], $session->uid);
}
If i only tick the searchtv checkbox it only runs the searchTV function and so on.. so i know it is being set and works.. just cannot get the feedback to the checkbox to say yes it was ticked when the search button was selected.
#medoix: Try changing this
<input type="checkbox" name="searchmovie" value="movie" <? echo isset($_SESSION['searchmovie']) ? 'checked' : ''; ?>"/>
to this
<input type="checkbox" name="searchmovie" value="movie" <?php if (isset($_SESSION['searchmovie'])) { echo 'checked="checked" '; } ?>/>
You realize that the portion of the code that checks $_SESSION['searchtv'] && $_SESSION['searchmovie'] near the bottom are both !isset. It'll only run if both aren't checked, rather than if they are.