When the admin user unchecks all the user groups does not clear the permissions from db and throws error. If no permissions are selected and the form is submitted it should clear the permissions column belonging to that id. But does not for some reason?
What is best way to make it work?
Error Number: 1064
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 'WHERE user_group_id = '10'' at line 4
UPDATE user_group SET name = 'Demonstration', permission = WHERE user_group_id = '10'
Filename: C:\Xampp\htdocs\codeigniter-project\system\database\DB_driver.php
Line Number: 330
User Group Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users_group_model extends CI_Model {
public function addUserGroup($data) {
$this->db->query("INSERT INTO " . $this->db->dbprefix . "user_group SET name = " . $this->db->escape($data['name']) . ", permission = " . (isset($data['permission']) ? $this->db->escape(serialize($data['permission'])) : '') . " ");
}
public function editUserGroup($user_group_id, $data) {
$this->db->query("UPDATE " . $this->db->dbprefix . "user_group SET
name = " . $this->db->escape($data['name']) . ",
permission = " . (isset($data['permission']) ? $this->db->escape(serialize($data['permission'])) : '') . "
WHERE
user_group_id = '" . (int)$user_group_id . "'
");
}
public function getUserGroup($user_group_id) {
$query = $this->db->query("SELECT DISTINCT * FROM " . $this->db->dbprefix . "user_group WHERE user_group_id = '" . (int)$user_group_id . "' ");
$user_group = array(
'name' => $query->row('name'),
'permission' => unserialize($query->row('permission'))
);
return $user_group;
}
}
View Form
<?php
if (trim(!$user_group_id)) {
echo form_open('admin/users_group/add', array('class' => 'form-horizontal', 'role' => 'form', 'id' => "form-user-group"));
} else {
echo form_open('admin/users_group/edit/' . $user_group_id, array('class' => 'form-horizontal', 'role' => 'form','id' => "form-user-group"));
}
;?>
<div class="form-group required">
<label class="col-sm-2 control-label" for="input-name"><?php echo $entry_name; ?></label>
<div class="col-sm-10">
<input type="text" name="name" value="<?php echo $name; ?>" placeholder="<?php echo $entry_name; ?>" id="input-name" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"><?php echo $entry_access; ?></label>
<div class="col-sm-10">
<div class="well well-sm" style="height: 150px; overflow: auto;">
<?php foreach ($permissions as $permission) { ?>
<div class="checkbox">
<label>
<?php if (in_array($permission, $access)) { ?>
<input type="checkbox" name="permission[access][]" value="<?php echo $permission; ?>" checked="checked" />
<?php echo $permission; ?>
<?php } else { ?>
<input type="checkbox" name="permission[access][]" value="<?php echo $permission; ?>" />
<?php echo $permission; ?>
<?php } ?>
</label>
</div>
<?php } ?>
</div>
<a onclick="$(this).parent().find(':checkbox').prop('checked', true);"><?php echo $text_select_all; ?></a> / <a onclick="$(this).parent().find(':checkbox').prop('checked', false);"><?php echo $text_unselect_all; ?></a>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"><?php echo $entry_modify; ?></label>
<div class="col-sm-10">
<div class="well well-sm" style="height: 150px; overflow: auto;">
<?php foreach ($permissions as $permission) { ?>
<div class="checkbox">
<label>
<?php if (in_array($permission, $modify)) { ?>
<input type="checkbox" name="permission[modify][]" value="<?php echo $permission; ?>" checked="checked" />
<?php echo $permission; ?>
<?php } else { ?>
<input type="checkbox" name="permission[modify][]" value="<?php echo $permission; ?>" />
<?php echo $permission; ?>
<?php } ?>
</label>
</div>
<?php } ?>
</div>
<a onclick="$(this).parent().find(':checkbox').prop('checked', true);"><?php echo $text_select_all; ?></a> /
<a onclick="$(this).parent().find(':checkbox').prop('checked', false);"><?php echo $text_unselect_all; ?></a></div>
</div>
</form>
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users_group extends MX_Controller {
private $error = array();
public function __construct() {
parent::__construct();
$this->lang->load('admin/user/users_groups', 'english');
$this->load->model('admin/user/users_group_model');
if(!$this->user->logged()) {
redirect('admin');
} elseif(!$this->user->hasPermissionAccess()) {
redirect('admin/error');
} else {
return true;
}
}
public function index() {
$this->document->setTitle($this->lang->line('heading_title'));
$this->getList();
}
public function add() {
if ($this->request->server['REQUEST_METHOD'] == 'POST') {
$this->load->model('admin/user/users_group_model');
$this->users_group_model->addUserGroup($this->request->post);
redirect('admin/users_group');
}
$this->getForm();
}
public function edit() {
$this->load->model('admin/user/users_group_model');
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
$user_group_id = $this->uri->segment(4);
$this->users_group_model->editUserGroup($user_group_id, $this->request->post);
$this->session->set_flashdata('success', $this->lang->line('text_success'));
redirect('admin/users_group');
}
protected function getForm() {
$this->load->model('admin/user/users_group_model');
$this->load->library('request');
$data['heading_title'] = $this->lang->line('heading_title');
$data['text_select_all'] = $this->lang->line('text_select_all');
$data['text_unselect_all'] = $this->lang->line('text_unselect_all');
$data['entry_name'] = $this->lang->line('entry_name');
$data['entry_access'] = $this->lang->line('entry_access');
$data['entry_modify'] = $this->lang->line('entry_modify');
$data['button_save'] = $this->lang->line('button_save');
$data['button_cancel'] = $this->lang->line('button_cancel');
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->lang->line('text_home'),
'href' => site_url('admin/dashboard')
);
$data['breadcrumbs'][] = array(
'text' => $this->lang->line('heading_title'),
'href' => site_url('admin/users_group')
);
$data['cancel'] = site_url('admin/users_group');
if (!empty($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
if (!empty($this->session->flashdata('success'))) {
$data['success'] = $this->session->flashdata('success', $this->lang->line('text_success'));
} else {
$data['success'] = '';
}
$user_group_id = $this->uri->segment(4);
$data['user_group_id'] = $user_group_id;
if (isset($user_group_id)) {
$data['action'] = site_url('user/users_group/add');
} else {
$data['action'] = site_url('admin/users_group/edit/' . $user_group_id);
}
if (!empty($user_group_id) && $this->request->server['REQUEST_METHOD'] != 'POST') {
$user_group_info = $this->users_group_model->getUserGroup($user_group_id);
}
if (isset($this->request->post['name'])) {
$data['name'] = $this->request->post['name'];
} elseif (!empty($user_group_info)) {
$data['name'] = $user_group_info['name'];
} else {
$data['name'] = '';
}
$ignore = array(
'blank',
'error',
'register',
'dashboard',
'column_left',
'menu',
'startup',
'login',
'logout',
'forgotten',
'reset',
'not_found',
'permission',
'footer',
'header'
);
$data['permissions'] = array();
$files = glob(APPPATH . 'modules/admin/' . 'controllers/*/*.php');
foreach ($files as $file) {
$part = explode('/', dirname($file));
$permission = basename($file, '.php');
if (!in_array($permission, $ignore)) {
$data['permissions'][] = $permission;
}
}
if (isset($this->request->post['permission']['access'])) {
$data['access'] = $this->request->post['permission']['access'];
} elseif (isset($user_group_info['permission']['access'])) {
$data['access'] = $user_group_info['permission']['access'];
} else {
$data['access'] = array();
}
if (isset($this->request->post['permission']['modify'])) {
$data['modify'] = $this->request->post['permission']['modify'];
} elseif (isset($user_group_info['permission']['modify'])) {
$data['modify'] = $user_group_info['permission']['modify'];
} else {
$data['modify'] = array();
}
$this->load->view('user/users_group_form', $data);
}
There seems to the problem on the permissions when its not being set it breaks up the query. I suggest just the active record on CI on this one. Example:
public function editUserGroup($user_group_id, $data)
{
$permission = (isset($data['permission']) ? serialize($data['permission']) : null);
$update = array(
'name' => $data['name'],
'permission' => $permission,
);
$this->db->where('user_group_id', $user_group_id);
$this->db->update($this->db->dbprefix . 'user_group', $update);
}
Or much cleaner using ->set() (personal preference):
public function editUserGroup($user_group_id, $data)
{
$permission = isset($data['permission']) ? serialize($data['permission']) : null;
$this->db->set('permission', $permission);
$this->db->set('name', $data['name']);
$this->db->where('user_group_id', $user_group_id);
$this->db->update($this->db->dbprefix . 'user_group', $update);
}
Related
Hi i am a blog page where i will be inserting blogs from admin panel.while inserting blogs into database i need to insert admin username as well into the database for the blogs.How to get the admin username and insert into blogs table.
Controller:
function addblogs()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<br /><span class="error"> ','</span>');
$this->form_validation->set_rules('blog_title','Blog Title');
$this->form_validation->set_rules('description','Blog Description');
if($this->form_validation->run()== FALSE)
{
$data['mainpage']='blogs';
$data['mode']='add';
$this->load->view('templates/template',$data);
}
else
{
$this -> blogs_model -> insertblogs();
$this->flash->success('<h2>blogs Added Successfully!</h2>');
redirect('blogs');
}
}
Model:
function insertblogs()
{
$username = $_SESSION['name'];
$title=$this->input->post('blog_title');
$result = str_replace(" ", "-", $title);
$data=array(
'blog_title'=>$this->input->post('blog_title'),
'blogtitle'=>$result,
'description'=>$this->input->post('description'),
'user'=>$username
);
$this->db->insert('blogs',$data);
}
}
View:
<?php
$form_attributes = array('name'=>'adds', 'id'=>'adds', 'enctype' => "multipart/form-data");
echo form_open('blogs/addblogs',$form_attributes);
?>
<div class="element">
<label for="blogtitle"><font color ="black">Blog Title</font></label>
<input class="text err" type="text" name="blog_title" id="blog_title" value="<?php echo set_value('blog_title');?>"/>
</div>
<div class="element">
<label for="description"><font color ="black">Blog Description</font></label>
<textarea name="description" id="myArea1" rows="4" cols="173"></textarea>
</div> <br/>
<div align="center">
<input type="submit" id="submit" value="Submit" />
</div>
<div class="clear"></div>
<?php echo form_close();?>
Login Controller:
if($this->session->userdata('admin_logged_in')){
$data['admin_details'] = $this->session->userdata('admin_logged_in');
$data['records']=$this->career_model->get_jobs_list();
$data['mode'] = "all";
$data['mainpage'] = "career";
$this->load->view('templates/template', $data);
}
else{
$this->load->view('login');
}
Login Model:
<?php
class login_model extends MY_Model
{
function login_user($user_name = '', $password=''){
$userdetails = array(
'user_name' => $user_name,
'password' => md5($password),
);
$this->db->where($userdetails);
$query = $this->db->get('login_details');
if($query->num_rows()):
$user = $query->result();
$sess_arry = array(
'user_id' => $user[0]->user_id,
'name' => $user[0]->name
);
$this->session->set_userdata('admin_logged_in', $sess_arry); //add admin details to session
return true;
else:
return false;
endif;
}
}
You can some change your model in insertblogs() method like that :
$this->load->library('session');
$logged_data = $this->session->userdata('admin_logged_in');
$user_id = $logged_data['user_id'];
$user_name = $logged_data['name'];
$username = $user_name;//$_SESSION['name'];
You can get the name of the logged-in user by:
$username = $this->session->userdata('username');
now you can use this $username to insert it in database or you can perform some other functionality.
I encountered problem with codeigniter. I want to update my profile page. I have problem when passing data from textbox in view to controller. In controller Profile.php, i have print_r $data that show no data get from view. Hope you guys can help me. Thank you.
View profile.php
if(isset($profile)){
?>
<?php echo validation_errors();?>
<?php echo form_open('profile/update_profile'); ?>
<div class="field half first"><input type="password" name="pass" placeholder="Password" value="<?php echo $profile['password']; ?>" /></div>
<div class="field half"><input type="password" name="con_pass" placeholder="Confirm Password" value="<?php echo $profile['con_password']; ?>" /></div>
<div class="field half"><input type="text" name="phone_no" placeholder="Phone Number" value="<?php echo $profile['phone_no']; ?>" /></div>
<li><?php echo form_submit(array('id' => 'submit', 'value' => 'Update')); ?></li>
</ul>
<?php echo validation_errors();?>
<?php echo form_close(); ?>
<?php
}
?>
Controller Profile.php
public function update_profile(){
$email = $_SESSION['email'];
// $data['profile'] = $this->profile_model->getprofile($email);
$data = array(
'password' => $this->input->post('pass'),
'con_password' => $this->input->post('con_pass'),
'phone_no' => $this->input->post('phone_no')
);
print_r($data);
if($this->profile_model->updateprofile($email,$data))
{
$this->load->view('provider/profile', $data);
}
}
Model profile_model.php
public function updateprofile($email, $data){
$this->db->where('email', $email);
return $this->db->update('user', $data);
}
}
Try like below with form validation
https://www.codeigniter.com/user_guide/libraries/form_validation.html
https://www.codeigniter.com/user_guide/libraries/form_validation.html#rule-reference
EXAMPLE
public function update_profile() {
$this->load->library('form_validation');
// You can change what you want set for the rules your self this just example:
$this->form_validation->set_rules('pass', 'pass', 'trim|required');
$this->form_validation->set_rules('con_pass', 'con_pass', 'trim|required|matches[pass]');
$this->form_validation->set_rules('phone_no', 'phone_no', 'trim|required');
if ($this->form_validation->run() == TRUE) {
// Update model stuff
}
$email = $_SESSION['email']; // User id instead of email.
$profile_data = $this->users_model->getprofile($email);
if ($this->input->post('pass')) {
$data['pass'] = $this->input->post('pass');
} elseif (!empty($profile_data)) {
$data['pass'] = $profile_data['pass'];
} else {
$data['pass'] = '';
}
if ($this->input->post('con_pass')) {
$data['con_pass'] = $this->input->post('con_pass');
} elseif (!empty($profile_data)) {
$data['con_pass'] = $profile_data['con_pass'];
} else {
$data['con_pass'] = '';
}
if ($this->input->post('phone_no')) {
$data['phone_no'] = $this->input->post('phone_no');
} elseif (!empty($profile_data)) {
$data['phone_no'] = $profile_data['phone_no'];
} else {
$data['phone_no'] = '';
}
$this->load->view('provider/profile', $data);
}
Model function
public function getprofile($email) {
$this->db->where('email', $email);
$query = $this->db->get('users');
return $query->row_array();
}
View Example
<?php echo form_open('profile/update_profile'); ?>
<?php echo validation_errors();?>
<input type="password" name="pass" value="<?php echo set_value('pass', $pass);?>"/>
<input type="password" name="con_pass" value="<?php echo set_value('con_pass', $con_pass);?>"/>
<input type="text" name="phone_no" value="<?php echo set_value('phone_no', $phone_no);?>" />
<?php echo form_submit(array('id' => 'submit', 'value' => 'Update')); ?>
<?php echo form_close();?>
I have a user registration form and it's working fine but would like to add an image upload feature inside it. This is basically what I'd like to achieve
ScreenShot 1
ScreenShot 2
So far, this is what I have done
Controller:
class Employees extends CI_Controller {
var $pgToLoad;
public function __construct() {
parent::__construct();
#this will start the session
session_start();
$this->load->helper(array('form', 'url'));
if(!isset($_SESSION['userId']) || !isset($_SESSION['userLevel']) || !isset($_SESSION['employeeid']) || !isset($_SESSION['firstname']) || !isset($_SESSION['lastname'])) {
redirect('home', 'location');
}
#this will load the model
$this->load->model('Contents');
#get last uri segment to determine which content to load
$continue = true;
$i = 0;
do {
$i++;
if ($this->uri->segment($i) != "") $this->pgToLoad = $this->uri->segment($i);
else $continue = false;
} while ($continue);
}
public function index() {
$this->main();
}
public function main() {
#set default content to load
$this->pgToLoad = empty($this->pgToLoad) ? "employees" : $this->pgToLoad;
$disMsg = "";
#this will delete the record selected
if($this->uri->segment(2) == 'delete') {
$this->deleteRecord();
}
#this will check if the post value is trigger
if(isset($_POST['addnew'])) {
$this->addRecord();
}
#this will check if the post value is trigger
if(isset($_POST['saveinfo'])) {
$this->updateinfo();
}
if($this->uri->segment(2) == 'add' || $this->uri->segment(2) == 'edit') {
#this display the form for products
$this->displayForm();
} else {
#this will display the job orders
$this->getAllEmployees();
}
if($this->uri->segment(2) == 'print') {
#this display the form for products
$this->pdf();
}
if($this->uri->segment(2) == 'do_upload') {
#this display the form for products
$this->do_upload();
}
#this will logout the user and redirect to the page
if($this->uri->segment(2) == 'logout') {
session_destroy();
redirect('home', 'location');
}
$data = array ( 'pageTitle' => 'Payroll System | ADMINISTRATION',
'disMsg' => $disMsg,
'mainCont' => $this->mainCont );
$this->load->view('mainTpl', $data, FALSE);
}
function do_upload(){
if($this->input->post('upload')){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload()){
$error = array('error' => $this->upload->display_errors());
$this->load->view('pages/employeesform', $error);
}
else{
$data=$this->upload->data();
$this->thumb($data);
$file=array(
'img_name'=>$data['raw_name'],
'thumb_name'=>$data['raw_name'].'_thumb',
'ext'=>$data['file_ext'],
'upload_date'=>time()
);
$this->Contents->add_image($file);
$data = array('upload_data' => $this->upload->data());
$this->load->view('pages/upload_success', $data);
}
}
else{
redirect(site_url('employees'));
}
}
function thumb($data){
$config['image_library'] = 'gd2';
$config['source_image'] =$data['full_path'];
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 275;
$config['height'] = 250;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
}
public function displayForm() {
$data['level'] = $this->Contents->exeGetUserLevel();
$data['status'] = $this->Contents->exeGetUserStatus();
$data['employee'] = $this->Contents->exeGetEmpToEdit($_SESSION['userId']);
if($this->uri->segment(2) == 'edit') {
$data['employee'] = $this->Contents->exeGetEmpToEdit($_SESSION['userId']);
$data['emp'] = $this->Contents->exeGetEmpToEdit($this->uri->segment(3));
$data['info'] = $this->Contents->exeGetUserInfo($this->uri->segment(3));
$this->mainCont = $this->load->view('pages/employeesform', $data, TRUE);
}
$this->mainCont = $this->load->view('pages/employeesform', $data, TRUE);
}
#this will add new record
public function addRecord() {
if(empty($_POST['fname']) || empty($_POST['mname']) || empty($_POST['lname']) || empty($_POST['empass']) || empty($_POST['emailadd']) || empty($_POST['gender']) || empty($_POST['datehired']) || empty($_POST['salary'])) {
$disMsg = "Please fill up the form completely.";
$_SESSION['disMsg'] = $disMsg;
} else {
$addNew = $this->Contents->exeAddNewRecord();
if($addNew['affRows'] > 0) {
$_SESSION['disMsg'] = "New Employee has been added.";
redirect('employees', 'location');
} else {
$disMsg = "Unable to add new employee.";
}
}
}
Views:
<?php echo form_open_multipart('employees/do_upload');?>
<img id="preview" style = "width: 200px; height: 200px;">
<input type="file" name = "userfile" id="input">
<br /><br />
<input type="submit" value="upload" name="upload" />
</form>
<form action="" method="post" enctype="multipart/form-data" id="empform" role="form" name="empform">
<div class="box-body">
<div class="row">
<div class="col-lg-6">
<div class="input-field col s12">
<label>Firstname</label>
<input type="text" id="fname" name="fname" class="form-control" value="<?php if(!empty($_POST['fname'])) { echo $_POST['fname']; } elseif(!empty($emp[0]['firstname'])) { echo $emp[0]['firstname']; } ?>">
</div>
<div class="input-field col s12">
<label>Middle Name</label>
<input type="text" id="mname" name="mname" class="form-control" value="<?php if(!empty($_POST['mname'])) { echo $_POST['mname']; } elseif(!empty($emp[0]['middlename'])) { echo $emp[0]['middlename']; } ?>">
</div>
<div class="input-field col s12">
<label>Password</label>
<input type="password" id="empass" name="empass" class="form-control" value="<?php if(!empty($_POST['empass'])) { echo $_POST['empass']; } ?>">
</div>
<div class="input-field col s12">
<label>Employee ID</label>
<input type="text" id="empno" name="empno" class="form-control" value="<?php if(!empty($_POST['empno'])) { echo $_POST['empno']; } elseif(!empty($emp[0]['employeeid'])) { echo $emp[0]['employeeid']; } ?>">
</div>
</div>
<div class="col-lg-4" style="padding-left:0;">
<?php if($this->uri->segment(2) == "edit") { ?>
<button type="submit" name="saveinfo" class="btn btn-lg btn-primary btn-block">Save</button>
<?php } else { ?>
<button type="submit" name="addnew" class="btn btn-lg btn-primary btn-block">Save</button>
<?php } ?>
</div>
</div>
</div>
</form>
As you can see in views, there are 2 forms. First form is for image upload and the other one is user registration form. How will I be able to include the image upload in the reg form and perform image upload, save user info and form validation once save button is clicked?
This is how I handle file uploads with form... it's a generic example but it should help.
View
<?php echo form_open_multipart('someController/someFunction') ?>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name">
</div>
<div class="form-group">
<label for="uploads">Upload a file</label>
<input name="uploads[]" id="fileupload" type="file" multiple="true">
</div>
<input type="submit">
<?php echo form_close() ?>
Controller
public function addRecordToTable()
{
$this->form_validation->set_rules('name' , 'Name', 'required');
if ($this->form_validation->run() == true) {
$array = array(
'name' => $this->input->post('name')
);
$record_id = $this->some_model->addData('some_table', $array);
$this->uploadFiles($record_id);
}
}
public function uploadFiles($record_id)
{
$config = array(
'upload_path' => FCPATH . "path\to\directory",
'allowed_types' => 'jpg|png|jpeg',
'overwrite' => TRUE,
);
$this->load->library('upload', $config);
$files = $_FILES['uploads'];
foreach ($files['name'] as $key => $filename) {
$_FILES['uploads[]']['name'] = $files['name'][$key];
$_FILES['uploads[]']['type'] = $files['type'][$key];
$_FILES['uploads[]']['tmp_name'] = $files['tmp_name'][$key];
$_FILES['uploads[]']['error'] = $files['error'][$key];
$_FILES['uploads[]']['size'] = $files['size'][$key];
$config['file_name'] = $filename;
$this->upload->initialize($config);
if (isset($_FILES['uploads[]']['name']) && !empty($_FILES['uploads[]']['name'])) {
if ( ! $this->upload->do_upload('uploads[]')) {
$error = array('error' => $this->upload->display_errors());
} else {
$uploads[] = $this->upload->data();
$array = array(
'record_id' => $record_id,
'filename' => $_FILES['uploads[]']['name'],
'size' => $_FILES['uploads[]']['size']
);
$this->some_model->addData('uploads', $array);
}
}
}
redirect(base_url() . 'someController/someFunction/' . $record_id);
}
Model
public function addData($table, $array)
{
$this->db->insert($table, $array);
return $this->db->insert_id();
}
Edit:
As per your comment, to insert data into multiple tables, simply modify the code in your controller so:
public function submitEmployeeDetails()
{
$this->form_validation->set_rules('value1' , 'Value 1', 'required');
$this->form_validation->set_rules('value2' , 'Value 2', 'required');
if ($this->form_validation->run() == true) {
$array1 = array(
'value1' => $this->input->post('value1')
);
$array2 = array(
'value2' => $this->input->post('value2')
);
$this->your_model->addData('employees', $array1);
$this->your_model->addData('employees_details', $array2);
}
}
So you have two arrays and you call the addData() function in the model, the first parameter specifies the name of the table and the second passes the associative array to be added.
<?php
$att = array('id' => 'survey_form', 'role' => 'ajax-form');
echo form_open('welcome/addsurvey', $att);
?>
<div class="span5 offset1" id="form_div">
<?php echo validation_errors('<div class="alert alert-danger reg_error">', '</div>'); ?>
<div class="form-group control-group warning">
<label for="SurveyTitle">Survey Title</label>
<input name="SurveyTitle" type="text" class="form-control" data-validation-required-message="Please enter a Survey Title" id="SurveyTitle" required placeholder="Please enter the Survey Title" value="<?php echo set_value('SurveyTitle'); ?>">
<p class="help-block"></p>
</div>
<div class="form-group control-group warning">
<label for="SurveyIntroduction">Survey introduction</label>
<textarea name="SurveyIntroduction" type="text" class="form-control" id="SurveyIntroduction" placeholder="Enter the Survey Introduction" value="<?php echo set_value('SurveyIntroduction'); ?>"></textarea>
</div>
<button type="submit" class="btn btn-large btn-success">Add Survey</button>
</div>
</form>
I am inserting data via the form above it works fine how do i show the fields on the form after insertion via the set_value as it isn't working for me right now.
Here is my controller function below:
public function addsurvey() {
if (isset($_POST['SurveyTitle']) && isset($_POST['SurveyIntroduction'])) {
$this->load->library('form_validation');
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->form_validation->set_rules('SurveyTitle', 'Survey Title', 'required');
$this->form_validation->set_rules('SurveyIntroduction', 'Survey introduction', 'required');
$this->form_validation->set_message('required', 'Survey Title and Survey Introduction cannot be empty');
if ($this->form_validation->run() == FALSE) {
$this->load->view('SurveyPage');
} else {
$today = date("Y-m-d H:i:s");
$UserId = "m123456789";
$SurveyTitle = $this->input->post('SurveyTitle');
$SurveyIntroduction = $this->input->post('SurveyIntroduction');
$SurveyLink = base_url() + rand() + $SurveyTitle;
$isDisabled = 0;
$db_query = $this->db->query("INSERT into survey(SurveyTitle,SurveyIntro,SurveyLink,DateCreated,CreatedBy,isDisabled) VALUES('" . $SurveyTitle . "','" . $SurveyIntroduction . "','" . $SurveyLink . "','" . $today . "','" . $UserId . "','" . $isDisabled . "')");
if ($this->db->insert_id($db_query)) {
$id = $this->db->insert_id();
$lastid['last_id'] = $id;
} else {
}
$data = $this->displayallsurveys();
$surveydata = $this->getsurveydatabasedonId($id);
$drpquestiontype = $this->displayquestiontypedropdown();
$chkvalidations = $this->displayvalidationscheckboxes();
$chkvalidationsother = $this->displayvalidationscheckboxesother();
$parent_data = array('drpquestiontype' => $drpquestiontype, 'chkvalidations' => $chkvalidations, 'chkvalidationsother' => $chkvalidationsother, 'lastid' => $lastid);
$parent_datasurveypage =array('data' => $data, 'surveydata' => $surveydata);
$this->load->view('SurveyPage', $parent_datasurveypage);
$this->load->view('question_data', $parent_data);
}
}
else
{
$data = $this->displayallsurveys();
$this->load->view('SurveyPage', array('data' => $data));
}
}
I want to import csv into mysql using codeigniter.
This is my source code.
view
<?php $this->load->view("admin/v_header");?>
<?php $this->load->view("admin/v_top_menu");?>
<?php $this->load->view("admin/v_sidebar");?>
<div class="content">
<div class="header">
<h1 class="page-title">Import Data Dosen</h1>
</div>
<?php $this->load->view("admin/v_alert_msg");?>
<form class="form-horizontal" action="<?php echo base_url();?>admin/save_dosen" method="POST" enctype="multipart/form-data">
<fieldset>
<legend>Import Data Dosen</legend>
<div class="control-group">
<label class="control-label"><b>Pilih File :</b></label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-barcode"></i></span>
<input type="file" name="csv_dosen" id="csv_dosen"/>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-primary">
<i class="icon-ok icon-white"></i>Save
</button>
</div>
</div>
</fieldset>
</form>
</div>
<?php $this->load->view("admin/v_footer");?>
library
<?php
error_reporting(0);
class Csv_impot {
var $csvfile, $delimitatore, $nometable;
var $_FIELD;
function csv_import($cf = "", $del = "", $nt = "") {
$this->csvfile = $cf;
$this->delimitatore = $del;
$this->nometable = $nt;
}
function export() {
$csvhandle = file($this->csvfile);
$field = explode($this->delimitatore, $csvhandle[0]);
$kolom = "";
foreach ($field as $array_kolom) {
$kolom.="`" . trim($array_kolom) . "`,";
}
$kolom = trim(substr($kolom, 0, -1));
//echo $kolom;
for ($i = 1; $i <= count($csvhandle); $i++) {
$valori = explode($this->delimitatore, $csvhandle[$i]);
$values = "";
foreach ($valori as $val) {
$val = trim($val);
if (eregi("NULL", $val) == 0)
$values.="'" . addslashes($val) . "',";
else
$values.="NULL,";
}
$values = trim(substr($values, 0, -1));
$query = "INSERT INTO " . $this->nometable . "(" . $kolom . ") values(" . trim($values) . ");";
$QUERY[$i] = $query;
}
return $QUERY;
}
}
controller
function import_dosen()
{
$this->data['title']="Import Data Dosen";
$this->load->view("admin/v_import_dosen", $this->data);
}
function save_dosen()
{
if(isset($_FILES['csv_dosen']['name']))
{
$csv_dosen=$_FILES['csv_dosen']['name'];
$handle = fopen($csv_dosen,"r");
$this->load->library('csv_import');
$csv=new csv_import(".$handle.",",","dosen");
$query=$csv->export();
$this->m_dosen->eksekusi($query);
// $check_file= explode(".", $csv_dosen);
// if(strtolower($check_file[1])=="csv")
// {
// $csv_dosen=$_FILES['csv_dosen']['temp_name'];
// $handle = fopen($csv_dosen,"r");
// while (($data = fgetcsv($handle, 1000,",")) !== FALSE)
// {
// echo "haha";
// }
// }
// else{echo "bukan file csv";}
//$handle = fopen($csv_dosen,"r");
//$csv_dosen_type=$_FILES['csv_dosen']['type'];
//$csv_dosen_size=$_FILES['csv_dosen']['size'];
}
//echo $handle;
}
models
<?php
class M_dosen extends CI_model
{
function __contruct()
{
parent::__construct();
}
function eksekusi($query)
{
//echo "<br/>";
//echo count($query);
for($i=1;$i<count($query);$i++)
{
$this->db->query($query[$i]);
//echo $query[$i];
//echo "<br/>"
}
}
}
?>
when I run this code, an erro display that [function.fopen]: failed to open stream: No such file or directory.
How I solved this promblem?
I hope you can help to solve this problem.
Thanks.
As per your library, you have to pass file name to your Csv_impot constructor. But you are passing file Handler.
so change your code as below.
//general oops method:
$csv=new csv_import($csv_dosen,",","dosen");
//In CI,
$this->load->library('csv_import',array($csv_dosen,",","dosen")); // no need to create object again. Array of values will be parameter for constructor.