Select dynamic record mysql Codeigniter - php

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.

Related

can't access value of input when i have it inside foreach loop (using post method)

I have a form contains one input (type button) and one image.
when i click on the button it supposed to delete the image (submit the form and get the value of the input which is the id of the image, using post method).
But i can't access the value of the input when i have it inside foreach loop.
because every input created inside foreach has the same name.
https://i.imgur.com/ed9Vv9m.png
i tried var_dump and there is just null value.
this is the form inside the camera view:
foreach($data['galleries'] as $gallery) :
?>
<div align=center>
<form action="<?php echo URLROOT; ?>/gelleries/camera"
method="post">
<input type="button" class="button" name="delete" id="abc"
value="<?php echo $gallery->galleryId; ?>" onclick="return
Deleteqry(<?php echo $gallery->galleryId; ?>);">
</div>
</form>
<?php endforeach; ?>
and this is the controller:
<?php
class Galleries extends Controller {
$this->galleryModel = $this->model('Gallery');
}
$galleries = $this->galleryModel->hiFive();
$datashow = [
'galleries' => $galleries
];
.....
public function camera(){
if (isset($_POST['delete']) && !empty($_POST["delete"])){
$imgid = $_POST["delete"];
$this->galleryModel->deleteimg($imgid);
echo "deleted!";
exit;
}
else
echo "error";
$this->view('/galleries/camera', $datashow);
}
and this is the model where i execute the queries:
<?php
class Gallery {
private $db;
public function __construct(){
$this->db = new Database;
}
.....
public function deleteimg($id){
$this->db->query("DELETE FROM galleries WHERE id = :id");
$this->db->bind(':id', $id);
if($this->db->execute()){
return true;
} else {
return false;
}
}
}
The Deleteqry inside onclick event of the button it's just a function where i check if i get the id of the image when i click on the button:
function Deleteqry(id)
{
if(confirm("Are you sure you want to delete this row?")==true)
window.location="http://localhost:8001/camagru/galleries/camera?
&del="+id;
return false;
}
Add hidden input field in your form block with value of gallery ID, like this:
<form ...>
<input type="button" class="button" name="delete" value="DELETE NOW">
<input type="hidden" name="GallID" value="<?php echo $gallery->galleryId;?>" >
</form>
And in your controller read that value from hidden field:
if (isset($_POST['delete']) && isset($_POST['GallID']) && !empty($_POST["delete"])){
$imgid = $_POST["GallID"];
$this->galleryModel->deleteimg($imgid);
echo "deleted!";
}
This works completly without javascript.

PHP MVC Delete Function Controller

I have made a MVC site that is displaying a databases records, each record is printed on its own line with a delete button beside it. I am having some issues with the delete button. When I click the delete button I am trying to sending it to my controller to handle.
The issues I am having are
I cant send the row id from the button.php to the controller (Have a strong suspicion that the code is wrong)
The delet function in the controller doesnt work, in the code below I have hard coded in the row ID that I want to delete but when I click the delete button I get the following error
Syntax error in SQL statement.You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'id=27' at line 1
Button.php
<?php
$result=$itemsDAO->getItems();
foreach ($result as $row) {
$uid = $row['id'];
?>
<form action="index.php" method="post">
<fieldset>
<input id='action' type='hidden' name='action' value='deleteItem' />
<p>
<div class="form-group">
<div class="controls">
<input type="hidden" id="fID" name="uid" value="<?php echo $uid; ?>">
<input type="submit" class="btn btn-success" value="Delete">
</div>
</div>
</p>
</fieldset>
</form>
<?php } ?>
Delete function in the controller
function deleteItem($parameters) {
$id = $parameters["fID"];
if ($this->model->deleteItem( $id )) {
$this->model->hasDeleteFailed = false;
$this->model->setDeleteItemConfirmation();
return (true);
}
else
$this->model->deleteItemError ( DELETE_ITEM_ERROR_STR );
}
Delete SQL
public function deleteItem($id) {
$delId = $id;
$sqlQuery = "DELETE FROM items";
$sqlQuery .= " WHERE id=$delId;";
$result = $this->getDbManager () -> executeQuery ( $sqlQuery );
}
Try this steps :
Check whether $parameters is properly passed to the deleteItem function (use echo $parameters or somthing)
If so check the query (DELETE * FROM 'thetable' WHERE id = $id)
Normally in a MVC site parameters pass through (site_url/controller/method/parameter) url. But while you are using a form, it's need to be a mechanism to capture your form variables.

Codeigniter checking checkbox value

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;

how to save featured data into featured table from product table in codeigniter

I hope you are doing well. I am new in codeigniter :::
I have two tables in database 1. tbl_product 2. tbl_featured_products. I get data from tbl_product in a form with foreach loop in checkbox system. After that I need to save product data into tbl_featured_products. I can not save it (multiple data in row ).... please help me out ..
My Question::
1. how can I save data into tbl_featured_products ?
2. how can I show image and others info and save data from view page ?
Controller:::
$data=array();
$data['featured_id']=$this->input->post('featured_id',true);
$data['product_id']=$this->input->post('product_id',true);
$data['product_name']=$this->input->post('product_name',true);
$data['product_price']=$this->input->post('product_price',true);
$data['product_image']=$this->input->post('product_image',true);
$this->sa_model->save_featured_product_info($data);
}
Model :::::
public function save_featured_product_info($data)
{
$this->db->insert('tbl_featured_products',$data);
}
view::::
<tr>
<td width="130">Product Name: </td>
<td>
<?php foreach($all_product as $values) { ?>
<input type="checkbox" name="product_name" value="<?php echo $values->product_name;?>"> <?php echo $values->product_name;?> <br>
<?php } ?>
</td>
</tr>
I would try the following:
first load data to your view
Controller:
function dataToView(){
$data = $this->sa_model->tbl_product_info($data); //gets information from your model db
$this->load->view('templates/home', $data); //sends data to the view
}
View:
<tr>
<td width="130">Product Name: </td>
<td>
<form id="product_form">
<?php foreach($all_product as $values) { ?>
<input type="checkbox" name="product_name" value="<?php echo $values->product_name;?>"> <?php echo $values->product_name;?> <br>
<?php } ?>
<input type="submit" />
</form>
</td>
</tr>
Javascript
<script>
$(document).ready(function(){
$('#product_form').submit(function(){
var url = 'controller/save';
$.post(url, function(result){
if (result){
//...your success function..
}
});
return false;
});
});
</script>
Controller
<?php
function save(){
$product = $this->input->post('product_name');//this will get your posted product into the controller
//...add your own function
if (works){
echo true;
}else{
echo false;
}
}
?>

Switching controllers and sending data in codeigniter

I have to devellop an internal web based application with codeigniter and I need to chain different forms (generate upon data choosen with previous form).
Right now, I tried to use form validation in the same method of the controller but the chaining only validate the first form, I tried also with $_SESSION variables but I have to send a large amount of data between each form. I tried with class variable (in controllers and models) but every time the form is send the variable are initialise...
So i wonder if there is a way to switch from a method to another one in my controller giving the data to the new controller.
my first form:
<p>Filtres: </p>
<br/><br/>
<form action="" method="post" id="form_ajout_manip" >
<label for="thematique[]">Thématique</label><br/>
<select name="thematique[]" size="20" multiple>
<?php
foreach($list_thema->result() as $thema)
{
echo "<option value='".$thema->THEMATIQUE_ID."'>".$thema->PARENT_THEMATIQUE_ID." - ".
$thema->NOM."</option>";
}
?>
</select>
<input type="hidden" value="true"/>
<br/>
<br/>
<br/>
<input type="submit" value="Rechercher" />
</form>
my second form:
<form action="" method="post" id="form_ajout_manip_cdt">
<label for="nom_manip" >Nom manipulation: </label>
<br/>
<input type="text" name="nom_manip"/>
<TABLE border="1">
<CAPTION><?php echo $data->num_rows.' '; ?>resuuultat</CAPTION>
<TR>
<?php
foreach($data->list_fields() as $titre)
{
echo '<TH>'.$titre.'</TH>';
}
?>
</TR>
<?php
foreach($data->result() as $ligne)
{
echo '<TR>';
foreach($ligne as $case)
{
echo '<TD>'.$case.'</TD>';
}
echo '<TD><input type="checkbox" name="cdt[]" value="'.$ligne->ID_CANDIDAT.'"
checked="true"</TD>';
echo '</TR>';
}
?>
</TABLE>
<br/><br/>
<input type="submit" value="créer"/>
</form>
Those are the two method of my controller
public function choix()
{
//controller for the second form
$this->info_page['title']='Ajout manipulation';
$this->load->view('ui_items/header',$this->info_page);
$this->load->view('ui_items/top_menu');
$this->load->view("manipulation/choix",$data);
}
public function filtre()
{
//controller for the first form
$this->form_validation->set_rules('thematique[]','Thematique','');
if($this->form_validation->run())
{
$data['data']=$this->manipulation_mod->select_par_filtre($this->input->post('thematique'));
//need to send $data to the second method "choix()"
}
else
{
$this->info_page['title']='Filtre ajout manipulation';
$this->load->view('ui_items/header',$this->info_page);
$this->load->view('ui_items/top_menu');
$data= array();
$data['list_op']= $this->candidat_mod->list_operateur();
$data['list_thema']= $this->thematique_mod->list_all_thematique();
$data['list_gene']= $this->candidat_mod->list_gene();
$this->load->view('manipulation/filtre', $data);
}
}
Have you any idea? I totally stuck...
Based on your clarification, let me give you an outline on what will work
View
Have both the forms in the same page
<? if(!$filtered): ?>
<input type="hidden" name="filtered" value="true"/>
/* Form 1 content here */
<? else: ?>
<input type="hidden" name="filtered" value="true"/>
/* Form 2 content here */
<? endif; ?>
Controller
You just need to use one controller
public function filter() {
$filtered = $this->input->post('filtered');
$data['filtered'] = $filtered;
if(empty($filtered)) {
/* Form validation rules for Form 1 */
/* Run form validation etc. */
/* Set title etc. for Form 1 */
} else {
/* Form validation rules for Form 2 */
/* Run form validation etc. */
/* Set title etc. for Form 2 */
}
/* Load view */
}
There might just be a better way to do this, but I am sure this will work. Good luck!

Categories