Joining tables with codeigniter active record - codeigniter

I am trying to update my code from query to codeigniter active records.
This here is my old code
public function get_categories($parent_id = 0) {
$language_id = "1";
$query = $this->db->query("SELECT * FROM " . $this->db->dbprefix . "category c LEFT JOIN " . $this->db->dbprefix . "category_description cd ON (c.category_id = cd.category_id) LEFT JOIN " . $this->db->dbprefix . "category_to_store c2s ON (c.category_id = c2s.category_id) WHERE c.parent_id = '" . (int)$parent_id . "' AND cd.language_id = '" . (int)$language_id . "' AND c2s.store_id = '" . (int)$language_id . "' AND c.status = '1' ORDER BY c.sort_order, LCASE(cd.name)");
return $query->result_array();
}
And i am trying to update it to new code below
The problem I am having is it not getting the correct result by the id. And since upgrading to CI-3 old code does not work.
public function get_categories($parent_id = 0) {
$this->db->select('*');
$this->db->from('category');
$this->db->join('category_description', 'category_description.category_id = category.category_id', 'left');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return false;
}
}
How can I use the codeigniter join properly. to be able to get my code to work.

after upgrading to Codeigniter 3.0 you need to update your database config file:
delete: $active_record = TRUE;
add: $query_builder = TRUE;
there is actually more to consider updating, the full documentation you find here:
http://www.codeigniter.com/user_guide/changelog.html
and
http://www.codeigniter.com/user_guide/installation/upgrade_300.html

Related

Laravel advance search

I have created a multiform search in laravel & it's not working properly
I have a table name candidates & there is a row named salary in which it has value like shown the the below image from 1 lac(s) to 39 lac(s)
The meaning it's not working properly is if i search min salary = 0 & max salary = 4 it's showing data between 0 to 4 but it's also showing data like 10 18 22
controller code
public function advance(Request $request)
{
$data = \DB::table('candidates');
if( $request->name){
$data = $data->where('name', 'LIKE', "%" . $request->name . "%");
}
if( $request->location){
$data = $data->where('location', 'LIKE', "%" . $request->location . "%");
}
if( $request->key_skills){
$data = $data->where('key_skills', 'LIKE', "%" . $request->key_skills . "%");
}
if( $request->gender){
$data = $data->where('gender', 'LIKE', "%" . $request->gender . "%");
}
if( $request->pref_loc){
$data = $data->where('pref_loc', 'LIKE', "%" . $request->pref_loc . "%");
}
if( $request->phoneno){
$data = $data->where('phoneno', 'LIKE', "%" . $request->phoneno . "%");
}
if( $request->email){
$data = $data->where('email', 'LIKE', "%" . $request->email . "%");
}
$min_ctc = $request->min_ctc;
$max_ctc = $request->max_ctc;
if ($min_ctc || $max_ctc) {
$data = $data->where('salary', '>=', $min_ctc);
$data = $data->where('salary','<=',$max_ctc);
}
$data = $data->paginate(10);
$data2 = $data->total();
return view('search', compact('data2'))->with('data',$data);
}
Thanks in advance
You are trying to search on string not on integer. In order to get the required result you have to type cast the string to integer or float and then perform the operation.
Here is the script that might help you.
if ($min_ctc || $max_ctc) {
$data = $data->whereRaw("CONVERT(SUBSTRING_INDEX(salary,' ', 1),UNSIGNED INTEGER) >= {$min_ctc}");
$data = $data->whereRaw("CONVERT(SUBSTRING_INDEX(salary,' ', 1),UNSIGNED INTEGER) <= {$max_ctc}");
}

laravel snappy pdf: getting an error the file was not created

I have about 1500 students in my database and I need to generate an invoice for each one. For this purpose I am using this library https://github.com/barryvdh/laravel-snappy . When I try to generate I get this error:
The file '/var/www/skmpastebimaslt/public_html/storage/checks/24767 Dominykas Butkevičius 1581703819.pdf' was not created (command: /usr/local/bin/wkhtmltopdf --lowquality '/tmp/knp_snappy5e46e28b5d61f2.13362077.html' '/var/www/skmpastebimaslt/public_html/storage/checks/24767 Dominykas Butkeviius 1581703819.pdf').
https://gyazo.com/3a3f60713601a663a1360cd65fee9914
Invoices are generated for four users then the app crashes. The most interesting thing is that even though the error says the file was not created but it was created, I can find it in my storage folder.
My code:
public function saveCheckPdf(Student $student, Check $check = null, $fileName = null)
{
if (empty($fileName)) {
$fileName = 'kvitas_' . time() . '.pdf';
}
$path = storage_path('checks/' . $fileName . '.pdf');
$this->renderCheckPdf($student, $check)->save($path);
return $path;
}
private function renderCheckPdf(Student $student, Check $check = null)
{
$bills = $this->billRepository->getCurrentSeasonBills($student->id);
$payments = $this->paymentRepository->getCurrentSeasonPayments($student->id);
$fileName = $student->fullname . ' kvitas';
$billsSum = $bills->sum('sum');
$paymentsSum = $payments->sum('sum');
if (empty($check)) {
$check = !empty($student->checks[0]) ? $student->checks[0] : false;
}
return newPDF::loadView('student.check_pdf', compact('student', 'payments', 'bills', 'billsSum', 'paymentsSum', 'fileName', 'check'));
}
Then I just loop through each user and call saveCheckPdf method in my controller like this
$this->pdfService->saveCheckPdf($student, null, $student->id . ' ' . $student->fullname . ' ' . time());
Maybe anyone faced the same problem?

checkout/session not returning order id while it is working on development site

I am working with magento and third party payment wallet Mobikwik. I got it working in my development site. But same code in production site does not return success page but return shopping cart empty after payment.
Path of file : community/wallet/controllers/Transactcontroller.php
$session = Mage::getSingleton('checkout/session');
$session->setQuoteId($session->getWalletQuoteId(true));
$walletConfig = Mage::getStoreConfig('payment/wallet');
$statuscode = $postdata['statuscode'];
$orderid = $postdata['orderid'];
$mid = $postdata['mid'];
$amount = $postdata['amount'];
$message = $postdata['statusmessage'];
$checksumReceived = $postdata['checksum'];
$all = "'" . $statuscode . "''" . $orderid . "''" . $amount . "''" . $message . "''" . $mid . "'";
if($checksumReceived != null){
$isChecksumValid = $this -> verifyChecksum($checksumReceived, $walletConfig['secret_key'], $all);
}
if($isChecksumValid){
// success
if ($this->_validateResponse()) {
Mage::getSingleton('checkout/session')->getQuote()->setIsActive(false)->save();
$order2 = Mage::getModel('sales/order')->loadByIncrementId($session->getLastRealOrderId());
$order1 = Mage::getModel('sales/order')->load($postdata['orderid']);
$total_amount = (double)$order2->getGrandTotal(); //// total amount from database for an order ////
if( ((double)$postdata['amount'] == (double)$order2->getGrandTotal()) AND ($session->getLastRealOrderId() == $postdata['orderid'])) {
// success code here and redirect to success page
else { // print error message }
$order2 is returning nothing but $order1 returning correct values.
Above code is working in development site. I found that problem is in production database.
Can anyone point me any correct direction!

Lof K2Scroller Module

I have been using K2 Scroller module developed by Land of Coder. When I use this module to display same category items in the items view the module displays items in the ascending order of the date created and it is the default and only setting available in the module parameter settings in the back-end. However, I want the module to display the items in date wise descending order. So I chose to edit the default code in the helper which I suppose is used to process items based on the back-end settings. And this is the part of the code in the helper file which I think controls the order:
public function __getList( $params ){
global $mainframe;
/*some irrelevant code removed*/
$condition = $this->buildConditionQuery( $params );
$limitDescriptionBy = $params->get('limit_description_by','char');
$ordering = $params->get( 'k2_ordering', 'created_desc');
$limit = $params->get( 'limit_items', 5 );
$ordering = str_replace( '_', ' ', $ordering );
$my = &JFactory::getUser();
$aid = $my->get( 'aid', 0 );
/*some irrelevant code removed*/
$extraURL = $params->get('open_target')!='modalbox'?'':'&tmpl=component';
$excludeIds = $params->get('exclude_ids', '');
$db = &JFactory::getDBO();
$date =& JFactory::getDate();
$now = $date->toMySQL();
$dateFormat = $params->get('date_format', 'DATE_FORMAT_LC3');
$limitDescriptionBy = $params->get('limit_description_by','char');
$isAuthor= $params->get('itemAuthor',0);
require_once ( JPath::clean(JPATH_SITE.'/components/com_k2/helpers/route.php') );
$query = "SELECT a.*, cr.rating_sum/cr.rating_count as rating, c.name as categoryname,
c.id as categoryid, c.alias as categoryalias, c.params as categoryparams, cc.commentcount as commentcount".
" FROM #__k2_items as a".
" LEFT JOIN #__k2_categories c ON c.id = a.catid" .
" LEFT JOIN #__k2_rating as cr ON a.id = cr.itemid".
" LEFT JOIN (select cm.itemid as id, count(cm.id) as commentcount from #__k2_comments as cm
where cm.published=1 group by cm.itemid) as cc on a.id = cc.id";
$query .= " WHERE a.published = 1"
. " AND a.access get('featured_items_show','0') == 0 ){
$query.= " AND a.featured != 1";
} elseif( $params->get('featured_items_show','0') == 2 ) {
$query.= " AND a.featured = 1";
}
if( trim($excludeIds) ){
$query .= " AND a.id NOT IN(".$excludeIds.") ";
}
$query .= $condition . ' ORDER BY ' . $ordering;
$query .= $limit ? ' LIMIT ' . $limit : '';
$db->setQuery($query);
$data = $db->loadObjectlist();
/*some irrelevant code removed*/
return $data;
}
/**
* build condition query base parameter
*
* #param JParameter $params;
* #return string.
*/
public function buildConditionQuery( $params ){
$source = trim($params->get( 'k2_source', 'k2_category' ) );
if( $source == 'k2_category' ){
$catids = $params->get( 'k2_category','');
if( !$catids ){
return '';
}
$catids = !is_array($catids) ? $catids : '"'.implode('","',$catids).'"';
$condition = ' AND a.catid IN( '.$catids.' )';
} else {
$ids = preg_split('/,/',$params->get( 'k2_items_ids',''));
$tmp = array();
foreach( $ids as $id ){
$tmp[] = (int) trim($id);
}
$condition = " AND a.id IN('". implode( "','", $tmp ) ."')";
}
return $condition;
}
Am I editing the right part of the code or am I missing something else.
I am looking forward to your help
Thanks.
Maybe the best way would be to modify the xml file of the module.
I looked at the code of Lof K2Scroller (v 2.2 for Joomla 2.5) and the different ordering options are there.
However if you want to modify the default option, you are in the right file, just replace 'created_desc' for 'created_asc' .

Codeigniter pagination problem

I basically can’t get the pagination bit to work, I did before I changed my database query and now I’m stuck.
My model looks like:
function get_properties($limit, $offset) {
$location = $this->session->userdata('location');
$property_type = $this->session->userdata('property_type');
if($property_type == 0)
{
$sql = "SELECT * FROM properties ";
}
// more queries here
$sql .= " LIMIT ".$limit.", ".$offset.";";
$query = $this->db->query($sql);
if($query->num_rows() > 0) {
$this->session->set_userdata('num_rows', $query->num_rows());
return $query->result_array();
return FALSE;
}
}
}
and my controller looks like:
function results() {
$config['base_url'] = base_url().'/properties/results';
$config['per_page'] = '3';
$data['properties_results'] = $this->properties_model->get_properties($config['per_page'], $this->uri->segment(3));
$config['total_rows'] = $this->session->userdata('num_rows');
$this->pagination->initialize($config);
$config['full_tag_open']='<div id="pages">';
$config['full_tag_close']='</div>';
$data['links']=$this->pagination->create_links();
$this->load->view('properties_results',$data);
}
please help…its screwing up!
The reason it's not working is that you never get the total_rows. You get the total_rows via this query, but it already has an offset and a limit:
$sql .= " LIMIT ".$limit.", ".$offset.";";
$query = $this->db->query($sql);
To fix this you should add a function to your model:
function get_all_properties()
{
return $this->db->get('properties');
}
Then in your controller, instead of:
$config['total_rows'] = $this->session->userdata('num_rows');
Do:
$config['total_rows'] = $this->properties_model->get_all_properties()->num_rows();
This should fix your pagination. Other than this your code has some strange things. E.g. return FALSE; in get_properties will NEVER execute. And why are you storing so much data in sessions. This is not necessary and not a good idea in my opinion.

Resources