When I update my database row. It for some reason update all the values as the same as last input which is very strange.
How can I get it working so all rows do not get updated with the value all the same?
This is how my database works.
$group = 'config'.
$key = example:'config_name'.
$value = what ever is typed in $key.
In my model I use foreach ($data as $key => $value) { It is very strange that it updates all values with the last input value.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_website_setting extends CI_Model {
public function editWebsite($group , $data, $website_id = 0) {
foreach ($data as $key => $value) {
// Make sure only keys belonging to this group are used
if (substr($key, 0, strlen($group)) == $group) {
if (!is_array($value)) {
$this->db->set('group', $group);
$this->db->set('value', $key);
$this->db->set('value', $value);
$this->db->set('website_id', $website_id);
$this->db->update($this->db->dbprefix . 'setting');
} else {
$this->db->set('group', $group);
$this->db->set('value', $key);
$this->db->set('value', $value);
$this->db->set('website_id', $website_id);
$this->db->update($this->db->dbprefix . 'setting');
}
}
}
}
}
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Website_settings extends Controller {
public function __construct() {
parent::__construct();
$this->lang->load('admin/setting/setting', 'english');
}
public function index() {
$this->document->setTitle($this->lang->line('heading_title'));
$data['entry_name'] = $this->lang->line('entry_name');
$data['entry_owner'] = $this->lang->line('entry_owner');
if (!empty($this->input->post('config_name'))) {
$data['config_name'] = $this->input->post('config_name');
} else {
$data['config_name'] = $this->settings->get('config_name');
}
if (!empty($this->input->post('config_owner'))) {
$data['config_owner'] = $this->input->post('config_owner');
} else {
$data['config_owner'] = $this->settings->get('config_owner');
}
$this->load->library('form_validation');
$this->form_validation->set_rules('config_name', 'Website Name');
$this->form_validation->set_rules('config_owner', 'Your Name');
if ($this->form_validation->run() == FALSE) {
return $this->load->view('setting/website_settings', $data);
} else {
$this->load->model('admin/setting/model_website_setting');
$this->model_website_setting->editWebsite('config', $this->input->post());
$this->session->set_flashdata('success', 'You have updated settings!');
redirect('admin/setting/website');
}
}
}
If i were you i would use the built in update_batch and will not place an update on every loop.
foreach ($data as $key => $value) {
// Make sure only keys belonging to this group are used
if (substr($key, 0, strlen($group)) == $group) {
if (!is_array($value)) {
// this is where you do the logic
// if the value is the same do not insert in the update array
// if the value is not the same then insert it on the update array
$update[] = array(
'group' => $group,
'value' => $key,
'website_id' => $website_id
);
} else {
$update[] = array(
'group' => $group,
'value' => $key,
'website_id' => $website_id
);
}
}
}
$this->db->update_batch($this->db->dbprefix . 'setting', $update , 'website_id');
sample on how to use update batch on your code not tested.
Related
I just want to insert dynamic generated input field data into database . My db table having three fields , id(Auto Increment), product_name and rate . I'm trying to insert bulk data into database using dynamically generated input fields where I can add/remove input fields manually.
I created the input fields as
<input class="form-control" placeholder="Product Name" name="prodname[]" type="text">
<input class="form-control" placeholder="Product Rate" name="prodrate[]" type="text">
This is my controller below
function Act_AddProducts() {
if ( $this->input->post( 'prodname' )&&$this->input->post( 'prodrate' )) {
foreach ( $this->input->post( 'prodname' ) as $key => $value ) {
$this->ProductModel->add_products( $value );
}
}
Model function is below
function add_products($val)
{
if($this->db->insert('tbl_product_master', array('product_name' => $val)))
{
return true;
}
else
{
return false;
}
}
Now the value is inserting into db but one at a time. So please help me to identify the issue with code. Also I don't really understand how to insert prodrate[] value into the same insert query.
Hope this will help you
Your controller Act_AddProducts should be like this :
function Act_AddProducts()
{
$prodnames = $this->input->post( 'prodname' );
$prodrates = $this->input->post( 'rate' );
if ( ! empty($prodnames) && ! empty($prodrates) )
{
foreach ($prodnames as $key => $value )
{
$data['product_name'] = $value;
/* make sure product_rate columns is correct i just guess it*/
$data['product_rate'] = $prodrates[$key];
$this->ProductModel->add_products($data);
}
}
}
Your model add_products should be like this :
function add_products($data)
{
if ( ! empty($data))
{
$this->db->insert('tbl_product_master', $data);
}
}
just pass input value to the model as it is, then use foreach inside model
function add_products($val)
{
foreach ( $val as $key => $value ) {
$this->db->insert('tbl_product_master', array('product_name' => $value );
}
}
TRY THIS
controller
function Act_AddProducts() {
$product_rate = $data = array();
$product_rate = $this->input->post( 'prodrate' );
$product_name = $this->input->post( 'prodname' )
if ( !empty($this->input->post( 'prodname' ))&&!empty($this->input->post( 'prodrate' ))) {
foreach ( $product_name as $key => $value ) {
$data['product_name'] = $value;
$data['product_rate'] = $product_rate[$key];
$this->ProductModel->add_products($data);
}
}
model
function add_products($data)
{
$product_name = $data['product_name'];
$product_rate = $data['product_rate'];
if($this->db->insert('tbl_product_master', array('product_name' => $product_name,'product_rate' => $product_rate)))
{
return true;
}
else
{
return false;
}
}
This is just for your reference.... A simple sample code for dynamic insert.
defined('BASEPATH') OR exit('No direct script access allowed');
class Checking extends CI_Controller {
public function index()
{
echo "<form method='post' action='". base_url("Checking/save") ."'>";
for($i=0;$i<=5;$i++)
{
echo "<input type='text' name='input_text[]'>";
}
echo "<button type='submit'>Submit</button></form>";
}
public function save(){
foreach($this->input->post("input_text") as $Row){
$this->db->insert("checking",array("input_text"=>$Row['input_text']));
}
}
}
create a controller as Checking.php, and run this .. you will get idea
For database
CREATE TABLE `checking` (
`ch` int(11) NOT NULL AUTO_INCREMENT,
`input_text` varchar(255) DEFAULT NULL,
PRIMARY KEY (`ch`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8
If you want upload bulk record then use insert_batch instead of simple insert
your Controller should be
function Act_AddProducts()
{
$product_rate = $_POST['prodrate'];
$product_name = $_POST['prodname'];
if(!empty($product_rate) && !empty($product_rate)){
$data_array = array();
foreach ($product_rate as $key => $value )
{
$tmp_array = array();
$tmp_array['product_name'] = $value;
$tmp_array['product_rate'] = $product_rate[$key];
$data_array[] = $tmp_array;
}
$this->ProductModel->add_products($data_array);
}
model should be
function add_products($data)
{
if($this->db->insert_batch('tbl_product_master', $data))
{
return true;
}
else
{
return false;
}
}
I'm just practicing using session in Codeigniter and i've got a Problem here's my controller
public function ajax_Addfees()
{
if($this->input->is_ajax_request())
{
$input = $this->input->post();
if($this->session->userdata('html')){
$html = $this->session->userdata('html');
}
$id = explode($input['fno']);
$html[$id] = ['amount' => $input['amount'], 'oldamount' => $input['deduction']];
$this->session->set_userdata('html', $html);
}
}
public function savetuition()
{
$this->Tuition_model->savefees();
redirect('tuitionsetup_con');
}
This is my model
public function savefees()
{
$fees = $this->session->userdata('html');
$feeslist = [];
if( !empty($fees) ) {
foreach ($fees as $key =>$value) {
array_push($feeslist, [
'amount' => $value['amount'],
'oldamount' => $value['oldamount'],
'f_no' => $key,
'sy_no' => $this->session->userdata('sy'),
'level_no' => $this->session->userdata('lvl'),
'id' => $this->session->userdata('id')
]);
$this->db->insert_batch('tuition', $feeslist);
} }
}
Well what I'm trying to do is to save data from session->set_userdata('html') to my database using codeigniter.
There's no error but it doesn't save data to database
You need to modify your model as:
public function savefees() {
$fees = $this->session->userdata('html');
$feeslist = array();
if( !empty($fees) ) {
foreach ($fees as $key =>$value) {
$feeslist[$key]["amount"] = $value['amount'];
$feeslist[$key]["oldamount"] = $value['oldamount'];
$feeslist[$key]["f_no"] = $key;
$feeslist[$key]["sy_no"] = $this->session->userdata('sy');
$feeslist[$key]["level_no"] = $this->session->userdata('lvl') ;
$feeslist[$key]["id"] = $this->session->userdata('id') ;
}
}
$this->db->insert_batch('tuition', $feeslist);
}
I am creating register webservice in Codeigniter. I want to get the response in json format, if the registration is successfull then the data will be returned in json format and if the data is already present then the json response will be returned. I have confusion in how to pass value from controller to view and convert it into json response. Below is my code:
Controller:
<?php
session_start(); //we need to start session in order to access it through CI
Class User_Signup extends CI_Controller {
public function __construct() {
parent::__construct();
// Load form helper library
$this->load->helper('form');
// Load form validation library
$this->load->library('form_validation');
// Load session library
$this->load->library('session');
// Load database
$this->load->model('signup_model');
}
public function registration($fname,$lname,$email) {
$data=array('first_name' => $fname,'last_name' => $lname,'email' => $email);
$result = $this->signup_model->registration_insert($data);
if ($result == TRUE) {
$this->load->view('signup_message',$data);
} else {
$this->load->view('signup_message',$data);
}
}
}
Signup_model (Model):
<?php
Class Signup_Model extends CI_Model {
// Insert registration data in database
public function registration_insert($data) {
// Query to check whether username already exist or not
$condition = "email =" . "'" . $data['email'] . "'";
$this->load->database();
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 0) {
// Query to insert data in database
$this->db->insert('user', $data);
if ($this->db->affected_rows() > 0) {
return true;
}
} else {
return false;
}
}
}
?>
View:
<?php
/* output in necessary format */
if ($format == 'json')
{
//header('Content-type: application/json');
echo str_replace('\/', '/', json_encode($posts));
} else
{
header('Content-type: text/xml');
echo '<posts>';
foreach ($posts as $index => $success)
{
if (is_array($success))
{
foreach ($success as $key => $value)
{
echo '<', $key, '>';
if (is_array($value))
{
foreach ($value as $tag => $val)
{
echo '<', $tag, '>', htmlentities($val), '</', $tag, '>';
}
}
echo '</', $key, '>';
}
}
}
echo '</posts>';
}
?>
http://localhost/MyProject/user_signup/registration/Amit/Kumar/amit
The view is unnecessary for returning json. Just return json_encode($your_object) right from the controller.
Either way, the method you are looking for is json_encode().
I am using codeigniter form validation lib and for some reason form is not updating this particular row. And there for not redirecting when form Submitted.
On my controller I use function like this
$this->load->model('admin/setting/model_setting');
$config_meta_title = $this->model_setting->edit_meta_title($this->input->post('config_meta_title'));
if (!empty($config_meta_title)) {
$data['config_meta_title'] = $this->input->post('config_meta_title');
} else {
$data['config_meta_title'] = $this->configs->get('config_meta_title');
}
But not updating database.
Model
<?php
class Model_setting extends CI_Model {
public function edit_meta_title() {
$data = array(
'group' => "config",
'key' => "config_meta_title",
'value' => $this->input->post('config_meta_title')
);
$this->db->where('setting_id', "2");
$this->db->update('setting', $data);
}
}
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Setting extends MY_Controller {
public function __construct() {
parent::__construct();
$this->lang->load('admin/setting/setting', 'english');
$this->lang->load('admin/english', 'english');
if ($this->session->userdata('user_id') == true) {
return true;
} else {
redirect('admin');
}
}
public function index() {
$this->load->library('form_validation');
$data['text_yes'] = $this->lang->line('text_yes');
$data['text_no'] = $this->lang->line('text_no');
$data['entry_meta_title'] = $this->lang->line('entry_meta_title');
$data['entry_maintenance'] = $this->lang->line('entry_maintenance');
$data['button_save'] = $this->lang->line('button_save');
$data['button_cancel'] = $this->lang->line('button_cancel');
$data['tab_store'] = $this->lang->line('tab_store');
$data['action'] = site_url('admin/setting');
$data['logout'] = site_url('admin/logout');
$data['cancel'] = site_url('admin/dashboard');
$this->load->model('admin/setting/model_setting');
$config_meta_title = $this->model_setting->edit_meta_title($this->input->post('config_meta_title'));
if (!empty($config_meta_title)) {
$data['config_meta_title'] = $this->input->post('config_meta_title');
} else {
$data['config_meta_title'] = $this->configs->get('config_meta_title');
}
if ($this->form_validation->run() == FALSE) {
return $this->load->view('setting/settings', $data);
} else {
redirect('admin/dashboard');
}
}
}
In your model, kindly try to pass it as a parameter:
public function edit_meta_title($config_meta_title) {
$data = array(
'group' => "config",
'key' => "config_meta_title",
'value' => $config_meta_title,
);
$this->db->where('setting_id', "2");
$this->db->update('setting', $data);
return $this->db->affected_rows();
}
I have fixed my issues now All working perfect
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Setting extends MY_Controller {
public function __construct() {
parent::__construct();
$this->lang->load('admin/setting/setting', 'english');
$this->lang->load('admin/english', 'english');
if ($this->session->userdata('user_id') == true) {
return true;
} else {
redirect('admin');
}
}
public function index() {
$data = array();
$data['text_yes'] = $this->lang->line('text_yes');
$data['text_no'] = $this->lang->line('text_no');
$data['entry_meta_title'] = $this->lang->line('entry_meta_title');
$data['entry_template'] = $this->lang->line('entry_template');
$data['entry_maintenance'] = $this->lang->line('entry_maintenance');
$data['button_save'] = $this->lang->line('button_save');
$data['button_cancel'] = $this->lang->line('button_cancel');
$data['tab_store'] = $this->lang->line('tab_store');
$data['action'] = site_url('admin/setting');
$data['logout'] = site_url('admin/logout');
$data['cancel'] = site_url('admin/dashboard');
$this->load->model('admin/setting/model_setting');
if (empty($config_meta_title)) {
$data['config_meta_title'] = $this->configs->get('config_meta_title');
}
if (empty($config_template)) {
$data['config_template'] = $this->configs->get('config_template');
}
$data['templates'] = array();
$directories = glob(APPPATH . 'modules/catalog/views/theme/*', GLOB_ONLYDIR);
foreach ($directories as $directory) {
$data['templates'][] = basename($directory);
}
if (empty($config_maintenance)) {
$data['config_maintenance'] = $this->configs->get('config_maintenance');
}
$this->load->library('form_validation');
$this->form_validation->set_rules('config_meta_title', 'Meta Title');
$this->form_validation->set_rules('config_template', 'Template');
$this->form_validation->set_rules('config_maintenance', 'Maintenance');
if ($this->form_validation->run() == FALSE) {
return $this->load->view('setting/settings', $data);
} else {
$config_meta_title = $this->model_setting->edit_meta_title($this->input->post('config_meta_title'));
$config_template = $this->model_setting->edit_template($this->input->post('config_template'));
$config_maintenance = $this->model_setting->edit_maintenance($this->input->post('config_maintenance'));
redirect('admin/dashboard');
}
}
}
Model
<?php
class Model_setting extends CI_Model {
public function edit_maintenance($config_maintenance) {
$data = array(
'group' => "config",
'key' => "config_maintenance",
'value' => $config_maintenance,
);
$this->db->where('setting_id', "1");
$this->db->update('setting', $data);
}
public function edit_meta_title($config_meta_title) {
$data = array(
'group' => "config",
'key' => "config_meta_title",
'value' => $config_meta_title,
);
$this->db->where('setting_id', "2");
$this->db->update('setting', $data);
}
public function edit_template($config_template) {
$data = array(
'group' => "config",
'key' => "config_template",
'value' => $config_template,
);
$this->db->where('setting_id', "3");
$this->db->update('setting', $data);
}
}
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.