Codeigniter checking checkbox value - php

I'm using CodeIgniter and I have a form with a checkbox that allows the user to check and remove their uploaded photo.
In my controller I use if(isset($checked) == 1) to check if the user wants to remove the photo.
$photo_to_table will set empty and pass to $this->tank_auth->update_user() to perform db update, and set photo field to become empty in table. Otherwise, it will remain the same photo.
But in my code, whether I check it or not, when I click UPDATE button, it keeps removing the photo, I wonder why is it happening?
Can someone please go through my code and give an advise?
Controller:
$user_id = $this->session->userdata('user_id');
$profile = $this->users->get_profile_by_id($user_id);
if(!empty($_FILES['photo']['name']))
{
//image upload process
}
else
{
$checked = $this->input->post('remove');
if(isset($checked) == 1)
{
$photo_to_table = '';
// here will do remove process to delete file in directory
}
else
{
$photo_to_table = $profile->photo;
}
}
if($this->form_validation->run()) { // validation ok
if(!is_null($data = $this->tank_auth->update_user(
$this->form_validation->set_value('name'),
$this->form_validation->set_value('country'),
$this->form_validation->set_value('website'),
$photo_to_table
)))
{
// success
$this->session->set_flashdata('msg', 'Profile has been updated');
redirect(current_url());
}
}
View:
<?php echo form_open_multipart($this->uri->uri_string()); ?>
<table border="0">
<?php
if(!empty($uphoto)){
?>
<tr>
<td>
<div>
<img src="<?php echo base_url().$userpath.$uphoto; ?>" />
</div>
<div>
<input id="remove" type="checkbox" name="remove">
<label for="remove">Remove photo</label>
</div>
</td>
</tr>
<?php
}
?>
Thanks.

What you need to do here is to change this line ...
if(isset($checked) == 1){
to
if((int) $checked == 1){
The reason is that the variable $checked will always be set whether its value is 1 or not. $checked = $this->input->post('remove'); will return NULL if the 'remove' is not set in the POST data.

Please write proper value in your checkbox :-
<input id="remove" type="checkbox" name="remove">
Write some value then check it :-
for e.g :
<input id="remove" type="checkbox" name="remove" value="1">
In php :-
if($checked == 1) {
// do whatever u want
}

Try:
<input id="remove" type="checkbox" name="remove" value="1">

remove isset
its because by default in your CI Controller you get input value using
$checked = $this->input->post('remove');
whether is has a value or not your variable now exist..

Use this if it can help.
$checked = (isset($_POST['checkbox']))?true:false;

Related

Select dynamic record mysql Codeigniter

I have following table "salary",And i want to select record according to checkbox selected ( dynamic )
Here is my table "salary"
id userId name salary
1 10 xyz 1000
2 12 abc 6000
3 11 sbb 9588
4 15 pyl 3000
Here is view file
<form method="post" action="<?php echo site_url().'/Admin/searchUser'?>" name="myForm" id="form_img" >
<?php
$i="1";
foreach($users as $user) { ?>
<tr>
<td><?php echo $i; ?></td>
<td class="txa_c"><input name="check[]" class="checkbox" type="checkbox" value="<?php echo $user['id']; ?>" ></td>
</tr>
<?php } ?>
</form>
<input type="submit" class="btn btn-pri1" value="Search" name="resume" >
</tr>
</form>
In controller file
function searchUser()
{
$result['crud'] = $this->Crud->getsearchUsers($_POST);
echo "<pre>";print_R($result['crud']);
}
In Model file
function getsearchUsers()
{
$ids=$_POST['check'];
//echo "<pre>";print_R($ids);
foreach($ids as $id)
{
$this->db->select('*');
$this->db->from('salary');
$this->db->where('userIdid',$id);
$row = $querys->result_array();
}
}
submit button should be the inside of closing form tag e.g.
<form>
<input type="submit" class="btn btn-pri1" value="Search" name="resume">
</form>
check if your Controller method is getting any Form POST array e.g.
<?php
function searchUser()
{
// make sure form is submitted
// With CodeIgniter’s built in methods you can simply do this:
if ($this->input->post()) {
// or PHP method
// if(isset($_POST) && !empty($_POST)){
// since the model method getsearchUsers don't have any input params
// no need to pass the inputs
$result['crud'] = $this->Crud->getsearchUsers();
// echo supports , separated statement too
echo '<pre>', print_r($result['crud']), '</pre>';
}
// show error that form is not submitted
die('Input Error: Please provide the valid inputs.');
}
?>
make sure there is no 403 error (CodeIgniter CSRF token because you
are using POST)
you can also use built-in 'where_in' to pass multiple where
conditions in your Model
<?php
function getsearchUsers()
{
// returns all post items with xss filter
$ids_array = $this->input->post('check', true);
$this->db->select('*');
$this->db->from('salary');
$this->db->where_in('userId', $ids_array);
// produces: WHERE userId IN ('1', '2')
$query = $this->db->get();
// check if records found
if ($query->num_rows() > 0) {
$row = $query->result_array();
// The $query result object will no longer be available
$query->free_result();
return $row;
}
// no record found
return FALSE;
}
?>
most important Always sanitize your users input before to use.

Refresh a PHP page after checking/unchecking a checkbox

I'm pretty new with PHP, so help please.
I need a web page in php with a checkbox. That page should refresh itself each time I do an action to the checkbox (so for both check or uncheck). Once it’s refreshed the page should keep the latest value of the checkbox.
I tried the following example modifying another code I took from StackOverflow, but it doesn’t works as I wish.
Any suggestion?
<?php
session_start();
$checked = "";
if($_SESSION['myaction'] != $_SESSION['value'])
{
if(isset($_POST['sharks']))
{
$_SESSION['value'] = $_POST['sharks'];
}
else
{
$_SESSION['value'] = '';
echo ":(";
}
$_SESSION['myaction'] = $_SESSION['value'];
}
?>
<form action="" method="POST">
<?php
print '<input name="sharks" type="checkbox" value="1" id="sharks" ';
if ($_SESSION['value'] == 1)
{
echo "checked='checked'";
}
$myaction = 2;
print ">";
?>
</form>
<form method='POST'>
<input name='sharks' type='checkbox' value='1' id='sharks' />
</form>
Some simpple, vanilla, Javascript that makes use of the localStorage ( or sessionStorage ). The click handler will set the checked status and on page load that value will help re-check, or not, the checkbox. Javascript is intended for this sort of purpose - though it is entirely possible to use PHP to re-check the checkbox when the page reloads provided it has some means to check a value against a stored value or a form submission.
document.addEventListener('DOMContentLoaded',()=>{
let chk=document.querySelector('input[type="checkbox"][name="sharks"]');
chk.checked=localStorage.getItem( chk.name )==null || localStorage.getItem( chk.name )=='false' ? false : true;
chk.addEventListener('click',e=>{
localStorage.setItem( chk.name, chk.checked )
location.reload();
});
});
Don't use a checkbox if you don't want the behaviour of a checkbox.
If you are submitting data, use a submit button. Users expect submit buttons to trigger a reload of the page.
<?php
$current_state = get_state_from_database_or_session_or_whatever();
if (isset($_POST['new_state'])) {
if ($_POST['new_state']) == "on") {
$current_state = "off";
} else {
$current_state = "on";
}
update_datebase_or_session_or_whatever_with_new_state($current_state);
}
$other_state = "off";
if ($current_state == "off") {
$other_state = "on";
}
?>
<p>The current state is <?php echo $current_state; ?></p>
<form method="post">
<button name="state" value="<?php echo $other_state; ?>">Set state to <?php echo $other_state; ?></button>
</form>
What you need to is pretty simple- assuming you are submitting the form on the same page.
<?php
$filterUsers=array();
if(isset($_GET['users'])){
foreach($_GET['users'] as $key){
$filterUsers[]=$key;
}
function valueInFilter($value){
if(in_array($value, $filterUsers)){
echo "checked";
}else{
echo "";
}
}
?>
<html>
<head>Filter </head>
<body>
<form method="get" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<input type="checkbox" name="users[]" value="john" id="1" <?php
valueInFilter("john",$filterUsers) ?>>
<label for="1"> John doe</label><br>
<input type="checkbox" name="users[]" value="john" id="2" <?php
valueInFilter("mayor",$filterUsers) ?>>
<label for="2"> John Mayor</label><br>
</form>
</body>
</html>
This is not an job for PHP like Professor Abronsius wrote.
Write it in JavaScript like this:
(() => {
// on page reloaded
const checkboxNode = document.getElementById('sharks')
if (localStorage.getItem('sharkCheckBox')) {
// the checkbox is stored as CHECKED
// e.g. check the checkbox again or what ever:
checkboxNode.checked = true
} else {
// the checkbox is stored as NOT checked
}
// handle the click
checkboxNode.addEventListener('click', function() {
// get the checkbox status
const isChecked = this.checked
// store the checked status inside the browser cache
localStorage.setItem('sharkCheckBox', isChecked)
// there are several ways to to an page reload. Here an example
// see details here https://stackoverflow.com/a/39571605/7993505
location.reload()
})
})()

Any way to identify which input type=submit was clicked on..?

I´m trying to do my graduation exam project, but I got stuck at one step.
I can rate other accounts, this is how it looks on the webpage.
Problem is when i am logged as adminstrator, I want to be allowed to delete the comments, but I dont know how to choose, which one delete input(type=submit) I pressed. Is there any way to determine which one i pressed..?
$komentare = $spojeni->prepare("SELECT komentare.ID_odesilatele,komentare.ID_prijemce,komentare.Stav,komentare.Nadpis,komentare.Text,uzivatele.Uzivatelske_jmeno FROM komentare JOIN uzivatele ON uzivatele.ID_uzivatele=komentare.ID_odesilatele WHERE ID_prijemce=?");
$komentare->bind_param("i", $_GET["id_uzivatele"]);
$komentare->bind_result($komidOd, $komidPr, $komStav, $komNadpis, $komText, $komJmeno);
$komentare->execute();
while ($komentare->fetch()) {
?>
<div class="komentar">
<img class="plusminus" src="obr/<?php
if ($komStav == 1) {
echo "plus.png";
}if ($komStav == 0) {
echo"minus.png";
}
?>" alt="">
<div class="nadpisKom">
<b><?php echo"$komNadpis"; ?></b>
</div>
<div class="zaslal">
Sent by <b><?php echo "$komJmeno"; ?></b>
</div>
<div class="textKom">
<?php echo"$komText" ?>
</div>
<?php
if (isset($_SESSION["id_uzivatele"]) && ($_SESSION["opravneni"] > 0 || $_SESSION["id_uzivatele"] == $komidOd)) {
?>
<input type="submit" name="smazat" value="Delete">
<?php
}
?>
</div>
The best way to do that you will keep the delete button invisible for normal user. to do that you can keep delete button inside a condition.
if(is_admin($user_id)){
<input type="submit" name="smazat" value="Delete">
}else{
// any thing you wanna show the normal user
}
in is_admin function you have to check the user is admin or not.
public function is_admin($id){
$sql = // your query will be here;
if($sql->num_rows > 0){
return true;
}else{
return false;
}
}

php form will not submit unless the checkbox is ticked

my form is unable to submit unless the checkbox is ticked, I am really unsure as to why this is.
further, if the checkbox is ticked it fails to update the database, there is no issue with the function I am using or the query as i have checked that directly on the db.
Any help would be hugely appreciated, and please feel free to ask any questions if there is anymore information i can give
<?php
include 'core/init.php';
protect_page();
include 'includes/overall/header.php';
$page = $_GET['page'];
$email = $_GET['user'];
$p_id = project_id_from_project_name($page);
$supervisor = supervisor_from_email($email, $p_id);
$user_id = user_id_from_email($email);
?>
<h1>Add A User to the Project</h1>
<?php
if (isset($_GET['form_submit']) === true && empty($_GET['form_submit']) === false) {
echo 'You\'re user has been added successfully!<br /><br />';
echo 'Please click here to return to Your Projects';
} else {
if (empty($_POST) === false && empty($errors) === true) {
$page = $_GET['page'];
$p_id = project_id_from_project_name($page);
$supervisor_update = ($_POST['supervisor'] == 1) ? 1 : 0;
$update_project_member_data = array(
'project_id' => "$p_id",
'project_name' => "$page",
'project_member_id' => "$user_id",
'supervisor' => "$supervisor_update"
);
update_project_member_data($p_id, $update_project_member_data);
header('Location: update_user.php?page=' . $page .'&user=' . $email .'&form_submit=1');
exit();
} else if (empty($errors) === false) {
echo output_errors($errors);
}
?>
<form action="" method="post">
<ul>
<li>
Email Address: <?php echo $email ?>
</li>
<li>
Set user as Supervisor?<br />
<input name="supervisor" type="checkbox" <?php if ($supervisor == 1) {?> checked="checked"<?php }?>/>
</li>
<li>
<input type="submit" value="Update User">
</li>
</ul>
</form>
<?php
}
include 'includes/overall/footer.php'; ?>
I believe the problem is with the condition you have:
empty($_POST) === false
Since your form is very basic and only has the one input. The $_POST array is only populated with values when that input is checked. Unchecked it doesn't pass any values in the $_POST array. Normally, the submit button would pass a value, but since you didn't have the "name" attribute on there, it doesn't.
You can either try adding the name attribute to the submit button or just add a hidden value inside the FORM element such as:
<input type="hidden" name="action" value="submitted" />
I think what is happening here is that there is no data to post if you do not check the box. You can check for the request method, $_SERVER['REQUEST_METHOD'] instead of empty($_POST).
edit: to clarify, the post happens but the if condition evaluates to false

show the form only if submit is not set

I am trying to show the form only if submit is not set, and if set then upload file and show link to the same page so that a new file could be uploaded again.
It shows the form even after I click on the submit button. I have not added an upload script now.
<body>
<?php
if (isset($_POST['submit']))
{
$output_form == 'no';
echo 'hiiiii';
}
else {
$output_form = 'yes';
}
if($output_form = 'yes')
{
?>
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="file" name="uploadpic" />
<input type="submit" value="Upload" name="submit" />
</form>
<?php
}
?>
</body>
$output_form == 'no'; should be $output_form = 'no';
if ($output_form = 'yes') should be if ($output_form == 'yes')
= is assignment, whereas == is a comparison.
Also, your form will use GET because you did not ask it to use POST with method="POST".
You're missing your method on the form element.
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
You can also use print_r($_POST) to see what's in the array.
Here's an example of it working, as well as the code.
http://www.wecodesign.com/demos/stackoverflow-7018639.php
if($output_form = 'yes')
should be
if($output_form == 'yes')
The way you have it now, you're assigning a value.
It should be
if($output_form == 'yes')
You doing assignment, use comparison:
if($output_form == 'yes')
Ensure that you're actually SETTING the no value as well:
$output_form == 'no';
Should be
$output_form = 'no';

Categories