update multiple rows after insert in codeigniter - codeigniter

After insert I want to update field with ($id.'mytext') where in db that field is empty for all rows.
table name: peca
columns:
id -autoincrement
A -varchar user insert
CB -varchar auto insert with update
MODEL WILL RETURN ALL ROWS WHERE CB=empty
function model1() {
$this->db->select('*');
$this->db->from('peca');
$this->db->where('CB', '');
//$this->db->where('id', $fileid);
$query = $this->db->get();
if ($query) {
return $query->result();
} else {
return false;
}
}
MODEL WILL update in db where CB=empty
function model2($dados = NULL) {
if ($dados !== NULL) {
// extract($dados);
$this->db->where('CB', '');
$this->db->update('peca', $dados);
return true;
} else {
return false;
}
}
CONTROLLER
$this->load->model('model_peca');
$resultadocadastropeca = $this->model_peca->model1($id);
$data = 'id' => $id;
$appointment = array('codigoean' => $data.'.PECA.');
$appointment = $this->model_peca->model2($appointment);
START TABLE
Previous values inserted from import so CB can only be generated after id exists
id|CB |
22| |
31| |
RESULTS
I'm changing CB to .PECA. in all rows where CB=empty but $id for each row is not passing
id|CB |
22|.PECA.|
31|.PECA.|
EXPECTED
id|CB |
22|22.PECA.|
31|31.PECA.|

I still don't fully understand what you want to do, but if you want to fetch something where a column is empty or null:
$this->db->where("WHERE yourColumn IS NULL OR yourColumn = ''");
As per your revised question, this should work:
$this->db->select('id');
$this->db->where('CB', '');
$q = $this->db->get('peca');
if ($q->num_rows() == 0) {
die('nothing to do here');
}
$res = $q->result();
foreach ($res as $item) {
$data[] = array('id' => $item->id, 'CB' => $item->id . '.PECA.');
}
$this->db->update_batch('peca', $data, 'id');

Related

Codeigniter count_all_results with having

I have composed a query using Codeigniter's Query Builder class. The query utilizes aliases and the having method. When I call the count_all_results method on this query, an exception occurs. Inspecting the log, I see that the query has stripped out the 'having' clauses. Is there a way to keep these clauses in while calling count_all_results? Thanks for your help.
EDIT: I first believed the problem was knowledge-based and not code-based and so did not share the code, but here it is. Please let me know if more is needed.
Here's the call on the model in the controller.
$where_array = array(
$parent_key.' is not NULL' => null
);
$search_post = $request_data['search'];
if (isset($request_data['filter'])) {
$filter_array = $request_data['filter'];
foreach ($filter_array as $filter_pair) {
if (isset($filter_pair['escape'])) {
$where_array[$filter_pair['filterBy']] = null;
} else {
if ($filter_pair['filterBy'] == 'table3_id') {
$where_array['table3.'.$filter_pair['filterBy']] = isset($filter_pair['filterId']) ?
$filter_pair['filterId'] : null;
} else {
$where_array[$table.'.'.$filter_pair['filterBy']] = isset($filter_pair['filterId']) ?
$filter_pair['filterId'] : null;
}
}
}
}
$like_array = array();
foreach ($request_data['columns'] as $key => $column) {
if (!empty($column['search']['value'])) {
$like_array[$column['data']] = $column['search']['value'];
}
}
$totalFiltered = $this->$model_name->modelSearchCount($search, $where_array, $like_array);
Here's the model methods.
public function modelSearchCount($search, $where_array = null, $like_array = null)
{
$this->joinLookups(null, $search);
if ($where_array) {
$this->db->where($where_array);
}
if ($like_array) {
foreach($like_array as $key => $value) {
$this->db->having($key." LIKE '%". $value. "%'");
}
}
return $this->db->from($this->table)->count_all_results();
}
protected function joinLookups($display_config = null, $search = null)
{
$select_array = null;
$join_array = array();
$search_column_array = $search ? array() : null;
$i = 'a';
$config = $display_config ? $display_config : $this->getIndexConfig();
foreach ($config as $column) {
if (array_key_exists($column['field'], $this->lookups)) {
$guest_model_name = $this->lookups[$column['field']];
$this->load->model($guest_model_name);
$join_string =$this->table.'.'.$column['field'].'='.$i.'.'.
$this->$guest_model_name->getKey();
$guest_display = $this->$guest_model_name->getDisplay();
if ($search) {
$search_column_array[] = $i.'.'.$guest_display;
}
$join_array[$this->$guest_model_name->getTable().' as '.$i] = $join_string;
$select_array[] = $i.'.'.
$guest_display;
} else {
$select_array[] = $this->table.'.'.$column['field'];
if ($search) {
$search_column_array[] = $this->table.'.'.$column['field'];
}
}
$i++;
}
$select_array[] = $this->table.'.'.$this->key;
foreach ($join_array as $key => $value) {
$this->db->join($key, $value, 'LEFT');
}
$this->db->join('table2', $this->table.'.table2_id=table2.table2_id', 'LEFT')
->join('table3', 'table2.table3_id=table3.table3_id', 'LEFT')
->join('table4', $this->table.'.table4_id=table4_id', 'LEFT')
->join('table5', 'table4.table5_id=table5.table5_id', 'LEFT');
$this->db->select(implode($select_array, ', '));
if ($search) {
foreach (explode(' ', $search) as $term) {
$this->db->group_start();
$this->db->or_like($this->table.'.'.$this->key, $term);
foreach ($search_column_array as $search_column) {
$this->db->or_like($search_column, $term);
}
$this->db->group_end();
}
}
$this->db->select('table2_date, '. $this->table.'.table2_id, table4_id, '. 'table5.table5_description');
}
Since count_all_results() will basically run a Select count(*) and not count the rows in your resultset (basically rendering the query useless for your purposes) you may use other Codeigniter methods to get the resultset and the row count.
Try running the query into a variable:
$query = $this->db->get();
From then, you can do pretty much anything. Besides returning the result with $query->result(); you can get the number of rows into another variable with:
$rownum = $query->num_rows();
You can then return that into your controller or even just return the $query object and then run the num_rows() method on the controller
To answer this question, count_all_results() transforms the original query by replacing your selects with SELECT COUNT(*) FROM table. the aliased column would not be selected, and the having clause would not recognize the column. This is why count_all_results() does not work with having.

Combining results into one if multiple

I have these two functions below
public function get_posts() {
$this->db->select('p.post_id, p.reply_id, p.user_id, u.username');
$this->db->from('post as p');
$this->db->join('user as u', 'u.user_id = p.user_id');
$this->db->where('p.post_id', $this->input->get('post_id'));
$this->db->or_where('p.reply_id', $this->input->get('post_id'));
// $this->db->group_by('p.user_id');
$query = $this->db->get();
return $query->result_array();
}
Results Output
SELECT * FROM `post` WHERE `post_id` = '1' AND `reply_id` = '0' AND `user_id` = '2'
SELECT * FROM `post` WHERE `post_id` = '3' AND `reply_id` = '1' AND `user_id` = '1'
SELECT * FROM `post` WHERE `post_id` = '5' AND `reply_id` = '1' AND `user_id` = '1'
Total Posts Function
public function total_posts_by_user($user_id, $reply_id, $post_id) {
$this->db->from('post');
$this->db->where('post_id', $post_id);
$this->db->where('reply_id', $reply_id);
$this->db->where('user_id', $user_id);
// $this->db->group_by('user_id');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->num_rows();
}
}
The total_posts_by user gets the number of post shown in image below
Question As you can see there are 2 admin row results showing. But I
would like them to be combined so it will just say row for admin and 2
posts.
I have tried using group_by() on get_post but dos not work
Controller
<?php
class Who_replied extends MX_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$data['posts'] = array();
$results = $this->get_posts();
foreach ($results as $result) {
$data['posts'][] = array(
'username' => $result['username'],
'total' => $this->total_posts_by_user($result['user_id'], $result['reply_id'], $result['post_id'])
);
$this->total_posts_by_user($result['user_id'], $result['reply_id'], $result['post_id']);
echo $this->db->last_query() . '</br>';
}
$data['total_posts'] = $this->total_posts();
return $this->load->view('default/template/forum/categories/who_replied_view', $data);
}
}
Use left join in first method because current it is using inner join. After that use group by
public function get_posts() {
$this->db->select('p.post_id, p.reply_id, p.user_id, u.username');
$this->db->from('post as p');
$this->db->join('user as u', 'u.user_id = p.user_id','left');
$this->db->where('p.post_id', $this->input->get('post_id'));
$this->db->or_where('p.reply_id', $this->input->get('post_id'));
$this->db->group_by('p.post_id');
$query = $this->db->get();
return $query->result_array();
}
and try. If still face same issue double check whether there are same TWO username admin
** Have you tried DISCTINCT?
hope it will help
I have found my solution from here using COUNT(p.user_id) AS total
public function get_posts() {
$this->db->select('p.post_id, p.reply_id, p.user_id, u.username COUNT(p.user_id) AS total');
$this->db->from('post as p');
$this->db->join('user as u', 'u.user_id = p.user_id');
$this->db->where('p.post_id', $this->input->get('post_id'));
$this->db->or_where('p.reply_id', $this->input->get('post_id'));
$this->db->group_by('p.user_id');
$query = $this->db->get();
return $query->result_array();
}

Call to a member function row() on a non-object

i am getting error Call to a member function row() on a non-object in codeigniter my controller is
public function edit_survey_pro($id)
{
$id = intval($id);
$survey = $this->model->get("surveys",array("ID" => $id),100000);
if (sizeof($survey) == 0) $this->template->error(lang("error_32"));
$this->template->loadContent("user/edit_survey_pro", array(
"survey" => $survey->row()
)
);
}
my model is
function get($table,$where='',$perpage=0,$start=0,$order_by='',$arr='')
{
$this->db->from($table);
if($perpage != 0 && $perpage != NULL)
$this->db->limit($perpage,$start);
if($where){
$this->db->where($where);
}
if($order_by){
$this->db->order_by($order_by);
}
if($arr=='')
$query = $this->db->get()->result();
else
$query = $this->db->get()->result('array');
if(!empty($query))
if($perpage != 0 && $perpage != NULL)
$result = $query;
else
$result = $query[0];
else
$result = array();
return $result;
}
here loadContent() is just load the content with view path
public function loadContent($view,$data=array(),$die=0){
//something to load the content
}
in my model I am getting the result as an array of object in $query and then it is returned as $result like this -
$query = $this->db->get()->result(); but at the controller $survey stores array of object and i want to show the content of that array of object ,previously I use
$this->template->loadContent("user/edit_survey_pro", array(
"survey" => $survey->row()
)
);
to get that data but the problem is $survey->row() cannot return that data bcoz it is not an object it is array of object so it can't be returned through row() method
so instead of this I just call the first element of that data like this-
$this->template->loadContent("user/edit_survey_pro", array(
"survey" => $survey[0]
)
);
Somehow its works for me bcoz I want to show the first row of the data
if sembody wants to show all data then I think he shuld try logic to increment the key value of that array of object for me it is $survey[] you can use foreach loop for increment the of value of the key element
The problems i see are your model, I will dissect it and add comments to your original code to point out the issues:
function get($table,$where='',$perpage=0,$start=0,$order_by='',$arr='')
//above there are problems, you are setting some of your parameters to
//equal blank, but below, in your conditionals, you are checking if they
// exist. They will always exist if they are set to blank. Fix them by
// setting them = NULL like this:
// get($table,$where=null,$perpage=0,$start=0,$order_by=null,$arr=null)
{
$this->db->select();// <-- you forgot this
$this->db->from($table);
if($perpage != 0 && $perpage != NULL)
//when will $perpage = null? , if never, then you dont need it.
$this->db->limit($perpage,$start);
if($where){
//change this to if(isset($where)). Also why do you use
//curly braces here, but not in the above if statement if only
//one line is affected in your if. I would remove the
//curly braces here.
$this->db->where($where);
}
if($order_by){
// change this to if(isset($order_by)). Same thing as
//above about the curly braces here
$this->db->order_by($order_by);
}
if($arr=='')
// change this to if(isset($arr)).
$query = $this->db->get()->result();
else
$query = $this->db->get()->result('array');
//change this to: $query = $this->db->get()->result_array();
if(!empty($query))
//change the above to if($query->num_rows > 0). Also, here since
//your code body is longer then one line, you will need curly braces
//around your if statement
if($perpage != 0 && $perpage != NULL)
//again, will $perpage ever be NULL? However, why do you need
//this conditional at all, if the limit above is already
//doing this job?
$result = $query;
else
$result = $query[0];
else
$result = array();
return $result;
}
after applying all the changes:
MODEL:
function get($table, $where=null, $perpage=0, $start=0, $order_by=null, $arr=null)
{
$this->db->select();
$this->db->from($table);
if($perpage != 0)
$this->db->limit($perpage, $start);
if(isset($where))
$this->db->where($where);
if(isset($order_by))
$this->db->order_by($order_by);
if(isset($arr)) {
$result = $this->db->get()->result_array();
} else {
$result = $this->db->get()->result();
}
return $result;
}
CONTROLLER
public function edit_survey_pro($id) {
$id = intval($id);
$survey = $this->model->get("surveys",array("ID" => $id),100000);
if (!$survey) {
$this->template->error(lang("error_32"));
} else {
$data["survey"] = $survey;
$this->template->loadContent("user/edit_survey_pro", $data);
}
}
I think when you use $this->db->get(), you need to pass the table name as param like this:
$this->db->get('table_name')->result();

links in pagination in codeigniter

in my view page,in the 1st form i have 2 select drop down...in the 1st drop down i am populating the value default from the controller...when u onchange the value in the 1st drop down,the selected value is passed to controller via javascript..in the controller,i get that 1st drop down value and load model and get value from model for the 2nd drop down and post it to view page...when u select the 2nd drop down value and click submit,the both drop down values are posted to controller after form validation and load model and get user information from the database and post it back again to view page ...this is the scenario for my view page..so,u can change the above both select drop down to get informations in the 2nd form in the same view page..now when i did pagination for my 2nd form user information,i am getting the links and data perfectly according to the limits and offsets..but,i am unable to retrieve the information when i click 2nd,3rd,4th..and rest on links while the informations are being posted from controller..so what can i do now?,,here is my code after i get both drop down values in the controller..
in my controller..
public function get_form_dept()
{
$this->load->helper(array('form', 'url'));
$this->load->library("pagination");
$this->load->library('form_validation');
$this->form_validation->set_rules('formation','Formation','required|required');
if($this->form_validation->run()== false) {
$this->viewstudent();
} else {
$config['base_url'] = base_url() . 'Incite/get_form_dept';
if($this->input->post('formation') == 1 && $this->input->post('department') == 1){
$config['total_rows'] = $this->db->get('user')->num_rows();
} else {
//$this->db->select('list_formation');
$query = $this->db->get_where('formation',array('id' => $this->input->post('formation')));
// echo $this->db->get_where('formation',array('id' => $this->input->post('formation')));
$row = $query->result();
foreach($row as $key) {
$get_formation = $key->list_formation;
echo $get_formation ."<br>";
}
$query1 = $this->db->get_where('department',array('id' => $this->input->post('department')));
$row1=$query1->result();
foreach($row1 as $key) {
$get_dept=$key->list_department;
echo $get_dept . "<br>";
}
//$array = array('formation' => $get_formation, 'department' => $get_dept);
//$config['total_rows']=$this->db->get('user',$array)->num_rows();
$query = $this->db->query("SELECT * FROM user where formation='$get_formation' and department='$get_dept'");
echo "SELECT * FROM user where formation='$get_formation' and department='$get_dept'" . "<br>";
$config['total_rows']=$query->num_rows();
//echo $row ."<br>";
//echo $row=$this->db->get('user',$array)->num_rows();
}
$config['per_page'] = 5;
//$config['uri_segment'] = 3;
//$choice = $config['total_rows'] / $config['per_page'];
// $config['num_links'] = round($choice);
$config['num_links'] = 2;
//$config['use_page_numbers'] = TRUE;
$config['suffix']= '?' . http_build_query($_GET, '', "&");
$this->pagination->initialize($config);
if($this->input->post('formation')== 1 && $this->input->post('department') == 1) {
// $this->db->limit($limit, $start);
$query_result = $this->db->get('user',$config['per_page'], $this->uri->segment(3));
$data['result']= $query_result->result();
} else {
$query = $this->db->get_where('formation',array('id' => $this->input->post('formation')));
$row = $query->result();
foreach($row as $key) {
$get_formation = $key->list_formation;
}
$this->db->where('id', $this->input->post('department'));
$query1 = $this->db->get('department');
$row1=$query1->result();
foreach($row1 as $key) {
$get_dept=$key->list_department;
//echo $get_dept;
}
$array = array('formation' => $get_formation, 'department' => $get_dept);
//$this->db->limit($limit, $start);
//$query = $this->db->get_where('user',$array);
$query_result=$this->db->get_where('user',$array,$config['per_page'], $this->uri->segment(3));
$data['result'] = $query_result->result();
}
$this->load->model('model_select_formation');
$data['formation'] = $this->model_select_formation->modelselectformation();
// query to fetch department
$data['dept']=$this->model_select_formation->get_department($data['formation_id']);
$data['formationid'] = $this->input->post('formation');
$data['departmentid'] = $this->input->post('department');
$this->load->view('viewstudent',$data);
}
}

Magento sets null value for non-selected attribute value in admin. It affects the frontend display. How to deal with it?

I've created a new attribute (type: dropdown) that is not a required field.
At this moment, every product shows in the frontend "my attribute: n/a".
After save anything in some product, magento write a null value inside catalog_product_entity_int table for this attribute.
But in the frontend the attribute now appear as "my attribute: No" instead of "N/A".
It looks like a bug, since I didn't touch in the attribute while editing the new product.
Is there a way to deal with it or to apply some rule in my phtml?
Actually this is not a bug. It's a feature.
N/A is displayed when there is no record in the table catalog_product_entity_int for that attribute.
When you add an attribute there are no values for that attribute for any product, but as soon as you save a product that has that attribute, a null value is inserted in the table (as you stated). So no value is different from null value.
All the magic happens here Mage_Catalog_Block_Product_View_Attributes::getAdditionalData().
These are the lines that interest you:
if (!$product->hasData($attribute->getAttributeCode())) { // no value in the database
$value = Mage::helper('catalog')->__('N/A');
} elseif ((string)$value == '') { // empty value in the database
$value = Mage::helper('catalog')->__('No');
}
If you want to change anything override this method.
If you change anything you might want to take a look at Mage_Catalog_Block_Product_Compare_List::getProductAttributeValue().
The same system is used for displaying attribute values in the compare products list.
I've ended up to create 2 observers... One that overrides getValue from Mage_Eav_Model_Entity_Attribute_Frontend_Default and other to override getAdditionalData in Mage_Catalog_Block_Product_View_Attributes as follows:
<?php
class Namespace_Module_Model_Entity_Attribute_Frontend_Default extends Mage_Eav_Model_Entity_Attribute_Frontend_Default{
public function getValue(Varien_Object $object)
{
$value = $object->getData($this->getAttribute()->getAttributeCode());
if (in_array($this->getConfigField('input'), array('select','boolean'))) {
$valueOption = $this->getOption($value);
if (!$valueOption) {
$opt = Mage::getModel('eav/entity_attribute_source_boolean');
$options = $opt->getAllOptions();
if ($options && !is_null($value)) { //added !is_null
foreach ($options as $option) {
if ($option['value'] == $value ) {
$valueOption = $option['label'];
}
}
}
}
$value = $valueOption;
} elseif ($this->getConfigField('input') == 'multiselect') {
$value = $this->getOption($value);
if (is_array($value)) {
$value = implode(', ', $value);
}
}
return $value;
}
}
and
<?php
class Namespace_Module_Block_Product_View_Attributes extends Mage_Catalog_Block_Product_View_Attributes
{
public function getAdditionalData(array $excludeAttr = array())
{
$data = array();
$product = $this->getProduct();
$attributes = $product->getAttributes();
foreach ($attributes as $attribute) {
if ($attribute->getIsVisibleOnFront() && !in_array($attribute->getAttributeCode(), $excludeAttr)) {
$value = $attribute->getFrontend()->getValue($product);
if (!$product->hasData($attribute->getAttributeCode()) || (string)$value == '') { //modified
$value = Mage::helper('catalog')->__('N/A');
} elseif ($attribute->getFrontendInput() == 'price' && is_string($value)) {
$value = Mage::app()->getStore()->convertPrice($value, true);
}
if (is_string($value) && strlen($value)) {
$data[$attribute->getAttributeCode()] = array(
'label' => $attribute->getStoreLabel(),
'value' => $value,
'code' => $attribute->getAttributeCode()
);
}
}
}
return $data;
}
}

Resources