Codeigniter get all rows from db - php

I'm working on task manager where have 2 types of user: Administrators(all privileges), and Users(limited privileges).
Here's my task function in controller
function task($id) {
$data = array(
'query' => $this->main_model->get_task($id),
'task_id' => $id,
);
$data2['comments'] = $this->main_model->get_comments($id);
$this->load->library('form_validation');
$this->load->helper('security');
$this->form_validation->set_rules('comment_text', 'comment_text', 'trim|required|strip_tags|xss_clean');
if ($this->form_validation->run() === FALSE)
{
if($this->main_model->get_task($id))
{
foreach ($this->main_model->get_task($id) as $tas)
{
$data = array(
'title' => $tas->task_name,
'desc' => $tas->task_description,
'date_created' => $tas->date,
'date_started' => $tas->task_start_date,
'deadline' => $tas->task_deadline,
'creator' => $tas->task_creator,
'owner' => $tas->task_owner,
'attach'=>$tas->attachment_name,
'status'=>$tas->task_status,
'priority'=>$tas->task_priority,
'task_id'=>$tas->ID_task,
'base_url' => base_url()
);
}
$data1 = array(
'emps' => $this->main_model->get_employees(),
'creator' => $this->main_model->get_details($id),
'owner' => $this->main_model->get_owner($id)
);
if ($this->session->userdata('employee_type') == 3) {
$qu = $this->main_model->permission();
$id = $this->session->userdata('id');
$id_emp = $this->uri->segment(3);
//foreach ($qu as $q) {
if (in_array($id, $qu[0]) && in_array($id_emp, $qu[0])) {
$this->load->view('task', array_merge($data, $data1, $data2));
}
else {
echo "No Permission to access this task";
}
}
}
}
else
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'doc|docx|pdf|txt|text|rtf|jpg|gif|png';
$config['max_size'] = '1024';
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
if ("You did not select a file to upload." != $this->upload->display_errors('','')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('task', $error);
}
else {
$this->main_model->set_comments($id);
redirect(current_url());
}
}
else {
$data = array('upload_data' => $this->upload->data());
$data1 = $this->upload->data();
$data2 = $data1['file_name'];
$this->main_model->set_comments($id);
$this->main_model->set_attachment($id, $data2);
redirect(current_url());
}
}
}
and my permission function in model:
function permission() {
$query = $this->db->get('employees_tasks');
$ret = $query->result_array();
return $ret;
}
What I'm trying to do is, get all data from database employee_tasks check if the ID_task and ID_employee are in the same row in database, but I can't get it working, I only getting first row of database, not the others, and that's my key problem, get all rows from db.
I tried query database with result, result_array, row, row_array, but for some reason everything is listing only first row in db. Any Help would be appreciated.

To get all results from a separate table using codeigniter Active record you can do like this
function permission() {
$this->db->select("*");
$this->db->from("employees_tasks");
$this->db->where('id', 'your id');
$query = $this->db->get();
return $query->result();
// OR
$query = $this->db->query("SELECT * from employees_tasks WHERE your condition");
return $query->result();
}
Hope it makes sense

Related

I want stored image delete when Updated with new image

I am new to codeigniter and I am having problem in edit item image, not that it don't get update as it do but there are too many images in the upload folder directory.
What I want to do is I want the previously stored image to be deleted in the upload directory when I update new image.
Here is my controller:
function edit($shop_id = null){
if ( ! $this->ion_auth->logged_in() OR ! $this->ion_auth->is_admin())
{
redirect('auth', 'refresh');
}
/* Breadcrumbs */
$this->data['breadcrumb'] = $this->breadcrumbs->show();
/* Variables */
$tables = $this->config->item('tables', 'ion_auth');
$this->data['shop_id'] = $shop_id;
/* Get all category */
$this->data['shopInfo'] = $this->shop_model->getShopInfo($shop_id);
//echo "<pre>";print_r( $this->data['shopInfo']);echo "</pre>";exit;
/* Validate form input */
$this->form_validation->set_rules('shop_name', 'Shop Name', 'trim|required');
$this->form_validation->set_rules('shop_latidude', 'Shop Latidude', 'trim|required');
$this->form_validation->set_rules('shop_longitude', 'Shop Longitude', 'trim|required');
if($this->form_validation->run() == true) {
$config['upload_path'] = './assets/uploads/shop/';
//die(var_dump(is_dir($config['upload_path'])));
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$img = "logo";
$img_upload = $this->upload->do_upload($img);
$data = $this->upload->data();
$file = array('file_name' => $data['file_name'] );
$data = array('upload_data' => $this->upload->data());
$photo = base_url().'assets/uploads/shop/'.$file['file_name'];
if($img_upload == 1 ) $post_photo = $photo;
else $post_photo = $this->input->post('hidden_photo');
if($this->input->post('status')){
$status = 1;
}else{
$status = 0;
}
$shopInfo = array(
'shop_name' => $this->input->post('shop_name'),
'merchant_id' => $this->input->post('merchant_id'),
'photo' => $post_photo,
'description' => $this->input->post('shop_desc'),
'registered_date'=> date('Y-m-d H:i:s'),
'is_active' => 1,
'shop_location' => $this->input->post('shop_loc'),
'shop_address' => $this->input->post('shop_add'),
'shop_phone' => $this->input->post('shop_ph'),
'shop_latitude' => $this->input->post('shop_latidude'),
'shop_longitude'=> $this->input->post('shop_longitude'),
'open_hour' => $this->input->post('open_hour'),
'close_hour' => $this->input->post('close_hour'),
'remark' => $this->input->post('remark'),
'approved' => $status
);
$this->shop_model->shopUpdate($shop_id, $shopInfo);
redirect(base_url() . 'admin/shop', 'refresh');
} else {
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
/* Load Template */
$this->data['merchant'] = $this->merchant_model->getAllMerchants();
$this->template->admin_render("admin/shop/edit", $this->data);
}
}
Here is my Model:
function shopUpdate($shop_id, $shopInfo) {
$this->db->where('shop_id', $shop_id);
if($shopInfo) {
$query = $this->db->update('shop', $shopInfo);
if ($query) {
return true;
} else {
return false;
}
} else {
return false;
}
}
function shopUpdate($shop_id, $shopInfo) {
$q = $this->db->select('photo')->where('shop_id', $shop_id)->get('shop');
if ($q->num_rows() > 0) {
$imgName = $q->row();
// image path must be './admin/shop'
unlink("./{image pathe}/".$imgName);
}
$this->db->where('shop_id', $shop_id);
if($shopInfo) {
$query = $this->db->update('shop', $shopInfo);
if ($query) {
return true;
} else {
return false;
}
} else {
return false;
}
}
you got file name when image got uploaded so get the file name where you are going to update and delete file first. Use unlink to delete file. run update query.
you just need to change in model for updating and deleting at same time.
First, check if new image uploading or not
$new_image = $_FILES['userfile']['name'] ? $_FILES['userfile']['name'] : '';
if($new_image != ''){
$old_image = $this->shop_model->getOlgImage($shop_id);
if(isset($old_image) && file_exists('image-path/photo.jpg')){
unlink('image-path/image');
}
}
Old image is now deleted. Upload new
$config['upload_path'] = './assets/uploads/shop/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$img = "logo";
Give name of your input type file name to $this->upload->do_upload() not variable
No need to add $this->upload->data() twice
if($this->upload->do_upload('userfile')){
$data = $this->upload->data();
$photo = base_url().'assets/uploads/shop/'.$data['file_name'];
$post_photo = $photo;
} else $post_photo = $this->input->post('hidden_photo');
if($this->input->post('status')){
$status = 1;
}else{
$status = 0;
}
Get old image
public function getOldImage($shop_id){
return $this->db->get_where('shop', ['shop_id' => $shop_id])->row()->photo;
}
First, you need to get image name from the database by ID then update record. Once the record is updated then you can delete that image the folder directory.
function shopUpdate($shop_id, $shopInfo) {
//fetch image name from the database by shop_id
$imageName = $this->db->select('photo')->where('shop_id', $shop_id)->get('shop');
$this->db->where('shop_id', $shop_id);
if($shopInfo) {
$query = $this->db->update('shop', $shopInfo);
if ($query) {
//record is updated successfully now delete that image from folder
if ($imageName->num_rows() > 0) {
unlink("./{image pathe}/".$imageName->row());
}
return true;
} else {
return false;
}
} else {
return false;
}
}
unlink()

How to remove this error: The filetype you are attempting to upload is not allowed

public function addAppdetails()
{ $dev_id = $this->sessionStart();
$this->load->library('form_validation');
$this->form_validation->set_rules('appname', 'App Name', 'required');
$this->form_validation->set_rules('platform', 'Platform', 'required');
//$this->form_validation->set_rules('category','App Category','required');
$this->form_validation->set_rules('description', 'App Description', 'required');
//$this->form_validation->set_rules('app_pic','App Pic','required');
//$this->form_validation->set_rules('file','App File','required');
if ($this->form_validation->run())
{
$appname = $this->input->post('appname');
$platform = $this->input->post('platform');
$category1 = $this->input->post('category');
$descripton = $this->input->post('description');
$category = implode(",", $category1);
echo "l";
$data1=$this->appFileupload();
echo "Break";
$data2=$this->appImageupload();
die;
foreach ($data1 as $dataArray)
{
$fileName=$dataArray['file_name'];
}
foreach ($data2 as $dataArray)
{
$imageName=$dataArray['file_name'];
}
$data = array('name' => $appname, 'platform' => $platform, 'description' => $descripton, 'category' => $category,'file_name'=>$fileName,'image_name'=>$imageName,'dev_id'=>$dev_id);
$this->Dev_model->addApp($data);
//$this->appImageupload();
echo "yolo";
}
else
{
$data['dataArray'] = $this->sessionStart();
$category = $this->input->post('category');
print_r($category);
$this->load->view('dev/addApp', $data);
}
}
public function appFileupload()
{
$config1['upload_path'] = './uploads/files';
$config1['allowed_types'] = 'apk|exe';
$this->load->library('upload', $config1);
if ( ! $this->upload->appFileUpload('file'))
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
return $data;
}
}
public function appImageupload()
{
$config2['upload_path'] = './uploads/appImages';
$config2['allowed_types'] = 'gif|jpg|png';
$config2['max_size'] = 1000000000;
$config2['max_width'] = 10240000;
$config2['max_height'] = 76800000;
$this->load->library('upload', $config2);
if ( ! $this->upload->appImageUpload('app_pic'))
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
return $data;
}
}
The output is as follows:
lBreak
Array ( [error] =>
The filetype you are attempting to upload is not allowed.
)
So, if I exchange the positions of appFileupload() and appImageupload() then it will give the same error for 'apk|exe' file and right now it is giving the error for appImageupload(). If you will ask how do I know about this? Then the answer is, I have checked their folder one gets uploaded but not the other.
CodeIgniter version is: 3.x
Add * in place of another type.
$config['allowed_types'] = '*';
I am just suggesting this for test purpose
Edit:
I am not sure but this will be helpful.
You could try looking at system/libraries/Upload.php line 199:
$this->_file_mime_type($_FILES[$field]);
Change that line to:
$this->_file_mime_type($_FILES[$field]); var_dump($this->file_type); die();
Well Lol, I'm answering my own question.
First, loading the library again with $config2 won't work because the library is already loaded once and $config1 will stay loaded. To load a new config use:
$this->upload->initialize($config2);

Add or edit data if already exist in database

Im trying to add or edit data depending if its already stored in the database. As you can see below im checking if user already exist with getuserid($id) loading the corresponding view but the problem is when i trigger add_user() or edit_user() as none of these methods are redirecting back as it should be. Any suggestions? This is the complete code http://pastebin.com/2G7D8ie4
public function getuserid($id = NULL){
if(!$id)
{
show_404();
}
$query = $this->Users_model->getuserid($id);
if($query == false){
$data = array('title'=>'Admin ::LxFPanamá::',
'content'=>'users/add_users_view',
'id'=>$id);
}else{
$data = array('title'=>'Admin ::LxFPanamá::',
'content'=>'users/edit_users_view',
'id'=> $query->id,
'staff_id'=> $query->staff_id,
'login'=> $query->login,
'password'=> $query->password
);
}
$this->load->view('themes/'.$this->config->item('theme_front').'.php', $data);
}
Model
public function getuserid($id){
$query = $this->db->get_where('users', array('staff_id' => $id));
if($query->num_rows() > 0){
return $query->row();
}else{
return false;
}
}
can you try making your model
public function getuserid($id){
$query = $this->db->get_where('users', array('staff_id' => $id));
$result=array();
foreach ($query->result() as $rows){
$result[]=$rows;
}
return $result;
}
and controller
if(count($query)>0){
$data = array('title'=>'Admin ::LxFPanamá::',
'content'=>'users/edit_users_view',
'id'=> $query->id,
'staff_id'=> $query->staff_id,
'login'=> $query->login,
'password'=> $query->password
);
}
else
{
$data = array('title'=>'Admin ::LxFPanamá::',
'content'=>'users/add_users_view',
'id'=>$id
);
}

Duplicate values insert into the database in Codeigniter

I am inserting some data into the database in my Codeigniter controller
function addsoothingmemory() {
$config['upload_path'] = './uploads2/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '500000';
$config['max_width'] = '100024';
$config['max_height'] = '100768';
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('soothing', $error);
} else {
$imagedata = $this->upload->data();
$data = array(
'image_path' => $imagedata['file_name'],
'title' => $this->input->post('title'),
'user_id' => $this->session->userdata("user_id"),
'feelingrate' => $this->session->userdata("feelingrate"),
'description' => $this->input->post('description')
);
$query = $this->favourite_db->getsoothingcount() + 1;
$this->favourite_db->add_soothingmemory($data);
$count = array('soothingcount' => $query);
$this->favourite_db->updateusercount($count);
$this->load->view('positivepast', $data);
}
}
Model
function add_soothingmemory($data) {
$this->load->database();
$this->db->insert('soothingmemory', $data);
$this->set_session();
return $data;
}
The problem is when the value is inserted into the database it inserts three times creating multiple/duplicate rows.
I had the same problem,
anyhow, in your model,
$this->db->limit(1);
$this->db->insert('soothingmemory', $data);
that way duplicates will be avoided.
Hope it helps
Make the following changes:
function addsoothingmemory() {
$config['upload_path'] = './uploads2/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '500000';
$config['max_width'] = '100024';
$config['max_height'] = '100768';
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('soothing', $error);
} else {
$imagedata = $this->upload->data();
$data = array(
'image_path' => $imagedata['file_name'],
'title' => $this->input->post('title'),
'user_id' => $this->session->userdata("user_id"),
'feelingrate' => $this->session->userdata("feelingrate"),
'description' => $this->input->post('description')
);
$query = $this->favourite_db->getsoothingcount() + 1;
$save = $this->favourite_db->add_soothingmemory($data);
// Move this code into the model
// $count = array('soothingcount' => $query);
if($save == true){
$this->favourite_db->updateusercount($query);
$this->load->view('positivepast', $data);
}else{
//do something else
}
}
}
In the model
function add_soothingmemory($data) {
$this->load->database();
$save = $this->db->insert('soothingmemory', $data);
//This condition will check, if the $data was save
if($save == true){
//If is save, it will set the session and return true
$this->set_session();
return true;
}else{
return false;
}
}

How to write an img path to MySQL using the file Uploader class and user model

I'm trying to add a final field to my project that contains a URL of the files that have been uploaded, if anyone could point me in the write direction for extending my model ?
I have included my codeIgniter Model & Controller code.
controller:
class Canvas extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index() {
$vars = array();
//$this->load->library('ChromePhp');
//$this->ChromePhp->log('test');
//$this->ChromePhp->log($_SERVER);
// using labels
// foreach ($_SERVER as $key => $value) {
// $this->ChromePhp->log($key, $value);
// }
// warnings and errors
//$this->ChromePhp->warn('this is a warning');
//$this->ChromePhp->error('this is an error');
$this->load->library('FacebookConnect');
$facebook=$this->facebookconnect->connect();
$vars['facebook'] = $facebook;
$user = $vars['user'] = $facebook->getUser();
$this->load->model('Users_Model');
// user already set up. Show thank you page
if($user != 0 && sizeof($_POST)>0) {
$this->do_upload();
$this->iterate_profile ($vars['user'],false,$_POST);
$this->load->view('canvas',$vars);
} else {
// user not set, show welcome message
$this->load->view('canvas',$vars);
}
}
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '20048';
$config['max_width'] = '10624';
$config['max_height'] = '10268';
$config['file_name'] = date("Y_m_d H:i:s");
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
function thank_you() {
$this->load->view('thank_you',$vars);
}
function remove() {
$vars = array();
$this->load->library('FacebookConnect');
$facebook=$this->facebookconnect->connect();
$vars['facebook'] = $facebook;
$vars['user'] = $facebook->getUser();
$this->load->model('Users_Model');
if($vars['user'] == 0) {
// user not set, redirect
redirect('/', 'refresh');
} else {
// user already set up. Remove
$this->load->model('Users_Model');
$this->Users_Model->remove($vars['user']);
}
$this->load->view('removed',$vars);
}
protected function iterate_profile ($user,$breadcrumb,$item) {
foreach($item as $key => $value) {
if(is_array($value)) {
$this->iterate_profile($user,$key,$value);
}
else {
if($breadcrumb) {
//echo '[' . $breadcrumb . '_' . $key . ']= ' . $value . ' <br />';
$key = $breadcrumb . '_' . $key;
}
if( ! $this->Users_Model->exists($user,$key)) {
// does not exist in the database, insert it
$this->Users_Model->add($user,$key,$value);
} else {
$this->Users_Model->update($user,$key,$value);
}
}
}
}
}
Model:
class Users_Model extends CI_Model {
protected $_name = 'users';
function add($id,$key,$value) {
$data = array(
'id' => $id,
'name' => $key,
'value' => $value
);
return $this->db->insert($this->_name, $data);
}
function update($id,$key,$value) {
$data = array(
'value' => $value
);
$this->db->where(array(
'id' => $id,
'name' => $key
));
return $this->db->update($this->_name, $data);
}
function exists($id,$key=null) {
if($key == null) {
$this->db->where(array(
'id' => $id
));
} else {
$this->db->where(array(
'id' => $id,
'name' => $key
));
}
$query = $this->db->get($this->_name);
if($query->num_rows() > 0) {
return true;
}
return false;
}
function remove($id) {
$data = array(
'id' => $id,
);
return $this->db->delete($this->_name, $data);
}
function all() {
$query = $this->db->get($this->_name);
$results = array();
if($query->num_rows() > 0) {
foreach($query->result() as $row) {
$results[]=$row;
}
}
return $results;
}
}
I don't think the question is very clear. But to me it seems you need to store the image path in the db. Otherwise you will need to perform a read directory on the upload path and then do something with the images.

Categories