Problems using batch_update in codeigniter - codeigniter

I read similar batch_update Qs but I still have issues. Thanks in advance for help! I receive error message ("One or more rows submitted for batch updating is missing the specified index.") for the following code:
Controller:
public function do_edit_page(){
$id = $this->input->post('page_id', TRUE);
$link_title = $this->input->post('page_link_title', TRUE);
$link = $this->input->post('page_link_sub_title', TRUE);
$this->content_model->update_links($id, $link_title, $link);
$this->index();
}
Model:
public function update_links($id, $link_title, $link){
$data = array(
array(
'page_id' => $id,
'link_title' => $link_title,
'link' => $link
)
);
$this->db->update_batch('content_links', $data, $id);
}

Check the CI documentation: http://ellislab.com/codeigniter/user-guide/database/active_record.html
The first parameter will contain the table name, the second is an associative array of values, the third parameter is the where key.
so the third parameter should be a column not data.

Related

CodeIgniter 3 code does not add data to database into 2 different tables (user_info & phone_info)

The problem is when I entered a new name no data is added. A similar thing happen when I entered an already existing name. Still, no data is added to the database. I am still new to CodeIgniter and not entirely sure my query builder inside the model is correct or not.
In the Model, I check if the name already exists insert data only into the phone_info table. IF name does not exist I insert data into user_info and phone_info.
Controller:
public function addData()
{
$name = $this->input->post('name');
$contact_num = $this->input->post('contact_num');
if($name == '') {
$result['message'] = "Please enter contact name";
} elseif($contact_num == '') {
$result['message'] = "Please enter contact number";
} else {
$result['message'] = "";
$data = array(
'name' => $name,
'contact_num' => $contact_num
);
$this->m->addData($data);
}
echo json_encode($result);
}
Model:
public function addData($data)
{
if(mysqli_num_rows($data['name']) > 0) {
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info',$phone_info);
} else {
$user_info = array(
'name' => $data['name']
);
$this->db->insert('user_info', $user_info);
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info', $phone_info);
}
}
DB-Table user_info:
DB-Table phone_info:
Extend and change your model to this:
public function findByTitle($name)
{
$this->db->where('name', $name);
return $this->result();
}
public function addData($data)
{
if(count($this->findByTitle($data['name'])) > 0) {
//.. your code
} else {
//.. your code
}
}
Explanation:
This:
if(mysqli_num_rows($data['name']) > 0)
..is not working to find database entries by name. To do this you can use codeigniters built in model functions and benefit from the MVC Pattern features, that CodeIgniter comes with.
I wrapped the actual findByName in a function so you can adapt this to other logic and use it elswehere later on. This function uses the query() method.
Read more about CodeIgniters Model Queries in the documentation.
Sidenote: mysqli_num_rows is used to iterate find results recieved by mysqli_query. This is very basic sql querying and you do not need that in a MVC-Framework like CodeIgniter. If you every appear to need write a manual sql-query, even then you should use CodeIgniters RawQuery methods.

Make request (pass data) from Command File to Controller in Lumen/Laravel

i get data (query) in command file and want to pass to controller via API (route)
here my request code in command file :
$request = Request::create('/create_data_account', 'post', ['data'=>$data]);
$create = $app->dispatch($request);
this is the route :
$router->post('/create_data_account', 'APIController#create_account_data_api');
and my controller :
public function create_account_data_api(Request $request)
{
$count = 0;
foreach ($data as $key => $value) {
$insert = Account::create([
'account_name' => $value->account_name,
'type' => $value->type,
'role_id' => $value->role_id
]);
if($insert){
$count++;
}else{
return $response = ['result'=>false, 'count'=>$count, 'message'=>'Internal error. Failed to save data.'];
}
}
return $response = ['result'=>true, 'count'=>$count, 'message'=>'Account data saved Successfully'];
}
i'm confused why passing data to controller not working with that code. anyone can give me solution ? Thanks
As you are making the request with ['data'=>$data]. That means all the data is contained on the key data of your array. So before the foreach loop, you need to add a declaration statement $data = $request->input('data'); to get data in $data variable.

Getting a "Call to a member function function() on a non-object" error in code igniter [duplicate]

This question already has answers here:
Call to a member function on a non-object [duplicate]
(8 answers)
Closed 10 years ago.
I'm very new to CodeIgniter and not an expert in OOP so please bear with me.
This is the function I have in my model:
function get_company(int $user_id, $fields = '*'){
$r = $this->db->query("SELECT $fields FROM ".$this->db->dbprefix('companies')." WHERE user_id=?", $user_id)->row();
return $r;
}
function get_profile($user_id, $fields = '*'){
$r = $this->db->query("SELECT $fields FROM ".$this->db->dbprefix('users_profiles')." WHERE user_id=?", $user_id)->row();
return $r;
}
This is in my controller that is calling that model:
function index(){
$this->load->model('profiles_m');
$profile = $this->profiles_m->get_profile($this->access->getUid());
$company = $this->profile_m->get_company($this->access->getUid());
$vars = array(
'profile'=>$profile,
'company'=>$company,
);
$this->_getTemplate()->build('account', $vars);
}
An in my view:
$company = array(
'name' => 'company',
'id' => 'company',
'value' => "$company->name",
'class' => 'styl_f validate[required] text-input input-xlarge',
'placeholder' => "$company->name"
);
echo $company['value']
The error I am getting is this: Call to a member function get_company() on a non-object in C:\..\application\modules\accounts\controllers\accounts.php
I am under the impression that I am receiving these errors because I am passing a non object through get_company() but the thing that confuses me is that this error does not come up for get_profile(); The get_profile() function in my model is very similiar to my get_company() function. What is causing this error? How can I get rid of it?
The problem is within your controller:
function index(){
$this->load->model('profiles_m');
$profile = $this->profiles_m->get_profile($this->access->getUid());
$company = $this->profile_m->get_company($this->access->getUid()); // Right here
$vars = array(
'profile'=>$profile,
'company'=>$company,
);
$this->_getTemplate()->build('account', $vars);
}
The $profile variable uses $this->profiles_m as the object, but $company misses the letter 's' in the object.
Try with this line instead:
$company = $this->profiles_m->get_company($this->access->getUid());
You have a typo, the line should read:
$company = $this->profiles_m->get_company($this->access->getUid());
Notice 'profiles_m' and not 'profile_m'.
$company = $this->profile_m->get_company($this->access->getUid());
replace 'profile_m' to 'profiles_m'

parsing arguments with Codeigniter form_validation callback for file input

I have a upload input and am trying to parse an argument to callback function via the CI form_validation library.
$this->form_validation->set_rules('orderfile', 'Order Form'," trim|callback_upload_check[$account_id]");
This calls:
public function upload_check($str, $id)
{
$errors = $this->do_upload($id);
if(isset($errors['error']))
{
$this->form_validation->set_message('upload_check', $errors['error']);
return FALSE;
}else{
return TRUE;
}
}
The Codeigniter Userguide states that when calling the function, the first argument is parsed as the second argument inside the function.
Neither arguments are parsed through. I found this post on the Codeigniter Forum
This seems to explain what is happening (variables are stripped). If i change the to <input type="text" /> the params work...
Is there anyway of getting around this problem?
you need to edit your code like this :
$this->form_validation->set_rules('orderfile', 'Order Form'," trim|callback_upload_check[".$account_id."]");
i also noticed that in your form_validation->set_rules you are not passing any value for id so in your function you should do :
public function upload_check($str, $id=0){..}
You need to change the function to:
public function upload_check($orderfile)
{
$errors = $this->do_upload($orderfile);
if(isset($errors['error']))
{
$this->form_validation->set_message('upload_check', $errors['error']);
return FALSE;
}else{
return TRUE;
}
}
I know this is an old question, but I was having the same problem, I finally realized the second parameter comes back in quotes, so if you pass an $id with the value 1, it actually comes back as "1".
So, to the original question, you need to callback the function like so:
$this->form_validation->set_rules('orderfile', 'Order Form'," trim|callback_upload_check[".$account_id."]");
And in your call back function:
public function upload_check($str, $id){
$actual_id=str_replace('"', "", $id)
}
$config =array(
array(
"field" => "userEmail",
"label" => ":userEmail:",
"rules" => "required|valid_email",
),
array(
"field" => "userPassword",
"label" => ":userPassword:",
"rules" => "required|min_length[8]",
),
);
$error_messages = array(
"required" => "{field} the field is required.",
"min_length" => "{field} the field value is so short",
"valid_email" => "{field} please valid email",
);
$this->form_validation->set_message($error_messages);
$this->form_validation->set_rules($config);
if($this->form_validation->run() == FALSE) {
$alert =preg_replace("/(\n)+/m", ' ', strip_tags(validation_errors()));
$explode =explode(':', $alert);
$arr =array();
for($i=1; $i < count($explode); $i+=2){
$y=$i;
$j =++$y;
$arr[$explode[$i]] = $explode[$j];
}
print json_encode($arr);
} else {
//process
}

In Codeigniter, how to pass a third parameter to a callback (form validation)?

I am currently using the Form Validation class (on Codeigniter) and setting rules.
It works like this with two parameters (codeigniter.com/user_guide/libraries/form_validation.html):
$this->form_validation->set_rules('username', 'Username', 'callback_test[abc]');
But what about a third parameter? And a fourth...? Is it possible?
It is not official but works
Split the parameter by ','
$this->form_validation->set_rules('article_big_image','Gambar Besar','callback_check_picture[article_big_image,edit]');
function check_picture($image,$param){
$param = preg_split('/,/', $param);
$field = $param[0];
$action = $param[1];
echo $field.$action;
}
Not without extended the system form validation class. For information on how to achieve this take a look at this article.
Alternatively you can access the post variables within your callback function using:
$this->input->post('field_name');
which may or may not help you out.
You can use Array for more parameters for more fields as like i did below:
$error = array(
array(
'field' => 'check', // the field name will come here
'label' => 'Check',
'rules' => 'required|here you can put the callback Function'
)
);
$this->form_validation->set_rules('article_big_image','Gambar','callback_check_picture[article_big_image,edit]');
function check_picture($image,$param){
$param = explode(',', $param);
$field = isset($param[0])?$param[0]:'';
$action = isset($param[1])?$param[1]:'';
echo $field.$action;
}
You can pass to the rule
|callback_handle_is_unique_value_combinations[val1,val2]
than,
public function callback_handle_is_unique_value_combinations($str, $field)
{
$fields = explode(',', $field);
$val1 = $fields[0];
$val2 = $fields[1];
and then you made your cponarisons

Resources