public function getQuestions($params = "",$page= "all", $count=false){
$this->db->query('SELECT questions.questions_id, questions.question_description,
questions.question_explanation, questions.created_date,
questions.updated_date, questions.is_active,
diffLevels.difficulty_levels_title
FROM '.TBL_QUESTION.' as questions
INNER JOIN '.TBL_DIFFICULTY_LEVELS.' as diffLevels
ON questions.fk_difficulty_levels_id = diffLevels.preference
WHERE questions.is_active=1');
$Q = $this->db->get();
if ($Q->num_rows() > 0) {
foreach ($Q->result() as $row) {
$data[] = $row;
}
}
$Q->free_result();
return $data;
}
This is my Query..and I did few many tweaks but it wont work..waiting for possible solutions? Thanks
Try this Query:
$this->db->select('
questions.questions_id,
questions.question_description,
questions.question_explanation,
questions.created_date,
questions.updated_date,
questions.is_active,
diffLevels.difficulty_levels_title
');
$this->db->from("questions");
$this->db->join("diffLevels",'questions.fk_difficulty_levels_id = diffLevels.preference' , 'inner');
$this->db->where("questions.is_active",1);
$query=$this->db->get();
$data=$query->result_array();
//echo $this->db->last_query();
//echo "<hr/>";
//echo "<pre>";
//print_r($query);
//exit;
I have directly used table name as "questions" and "diffLevels",Please change accordingly.
Related
Using Codeigniter 3, I would like to display all the records from a table in a MySQL database. I'd also like to include the number of records selected.
For example;
Showing x number of records;
record 1
record 2
record 3
etc
Currently I have the following (which works);
// select all records
public function selectRecords() {
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
return $query->result_array();
}
// count all records
public function countRecords() {
$this->db->select('count(*) as count');
$this->db->from('records');
$query = $this->db->get();
return $query->row();
}
My question is do I need two separate queries in order to achieve this (select and count)?
Is there a more efficient way of achieving what I want?
You can do something like this :
public function selectRecords()
{
$query = $this->db->get('records');
if ($query->num_rows() > 0 )
{
$records = $query->result_array();
$data['count'] = count($records);
$data['all_records'] = $records;
return $data;
}
}
Pass it to the view from your controller :
$data = $this->model_name->selectRecords();
/*print_r($data) to see the output*/
$this->load->view('your_view',$data);
In view :
<?php echo $count .' number of records';?>
you can do only:
public function selectRecords() {
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
return $query->result_array();
}
and
$records = $this->selectRecords();
$count = count($records);
In The first function itself you can get the count using $query->num_rows() function
public function selectRecords() {
$return = array();
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
$return['count'] = $query->num_rows();
$return['records'] = $query->result_array();
return $return;
}
try this
it will help you to provide pagination for records
public function selectRecords($params = array(), $count = false) {
$offset = isset($params['offset']) ? $params['offset'] : '';
$limit = isset($params['limit']) ? $params['limit'] : '';
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
if ($count) {
return $this->db->get()->num_rows();
}
if (empty($offset) && !empty($limit)) {
$this->db->limit($limit);
}
if (!empty($offset) && !empty($limit)) {
$this->db->limit($limit, $offset);
}
$result = $this->db->get()->result();
return $result;
}
I wanting to be able to join two tables togeather.
How ever because I my forum table has column "name" and my forum_categories column "name"
I am not able to display both names.
On my select() if I use like $this->db->select('f.name, fc.name', false); it only displays name from forum_categories
array(1) { [0]=> array(1) { ["name"]=> string(17) "News & Discussion" } }
Question how can I get both names to show from both columns and
tables.
Note: I only want to be able to use $result['name'] in my foreach loop.
So the out put I would like it to be
General
News & Discussion
Lounge
I have looked at
CodeIgniter ActiveRecord field names in JOIN statement
codeigniter - select from 2 tables with same column name
Model
public function get_forums() {
$this->db->select('f.name, fc.name', false);
$this->db->from('forum as f');
// tried $this->db->join('forum_categories as fc', 'fc.forum_id = f.forum_id');
$this->db->join('forum_categories as fc', 'fc.forum_categories_id = f.forum_id');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return false;
}
}
Controller
<?php
class Forums extends MY_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$data['label'] = '';
$data['forums'] = array();
$results = $this->get_forums();
var_dump($results);
if (isset($results)) {
foreach ($results as $result) {
$data['forums'][] = array(
'name' => $result['name'], // Only want to use single variable.
);
}
}
$data['header'] = Modules::run('admin/common/header/index');
$data['footer'] = Modules::run('admin/common/footer/index');
$this->load->view('template/forum/list_forum_view', $data);
}
public function get_forums() {
$this->db->select('f.name, fc.name', false);
$this->db->from('forum as f');
$this->db->join('forum_categories as fc', 'fc.forum_categories_id = f.forum_id');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return false;
}
}
}
update
works fine with code below but would rather just use one lot of join()
public function get_forums() {
$this->db->select("*");
$this->db->from('forum');
$query = $this->db->get();
foreach ($query->result_array() as $f) {
$data[] = array(
'name' => $f['name']
);
$this->db->select("*");
$this->db->from('forum_categories');
$query = $this->db->get();
foreach ($query->result_array() as $fc) {
$data[] = array(
'name' => $fc['name']
);
}
}
return $data;
}
Try This , It Will Work .
public function get_forums() {
$this->db->select('f.name as forum_name, fc.name as forum_categories_name', false);
$this->db->from('forum f');
// tried $this->db->join('forum_categories fc', 'fc.forum_id = f.forum_id');
$this->db->join('forum_categories fc', 'fc.forum_categories_id = f.forum_id');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return false;
}
}
From what i see in your updated question. What you need is UNION and not JOIN. You can use get_compiled_select() to build both query before concat with UNION.
public function get_forums() {
$forum = $this->db->select('name')->get_compiled_select('forum');
$forum_categories = $this->db->select('name')->get_compiled_select('forum_categories');
$query = $this->db->query($forum.' UNION '.$forum_categories);
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return false;
}
}
Simply use
AS
keyword, because when you try to print it, that AS keyword give you optional name for your column.
Here i have two table which have same column name "name" so i have changed those with AS keyword.
Ex:
$this->db->select('tbl_category.id_category,tbl_category.name AS cat_name,
tbl_subject.id_subject,tbl_subject.name AS sub_name');
In result
Array ( [0] => Array ( [id_category] => 9 [cat_name] => OL [id_subject] => 13 [sub_name] => Science )
So it is simple solution from the SQL language
How can I join the two arrays from controller? I tried to use AND operator as shown below but I failed. How can I make it possible?
function view_product($category_id)
{
$category_id=$this->uri->segment(3);
$this->load->model('select');
$this->data["products"]=$this->select->get_products($category_id);
$this->data["prices"]=$this->select->get_price($category_id);
$this->load->view("header");
$this->load->view("products",
$this->data);
}
here is my view:
<?php
$n=0;
foreach(($products as $product) && ($prices as $price) ) {
$n++;
echo '<tr><td>' .$n .'</td><td>'.$product['product_id'].'</a></td>
<td>'.$product['product_name'].'</td><td>'.$product['product_description'].'</td><td>'.$price['price_per_unit'].'</td><td>'.$price['price_per_item'].'</td></tr>';
}
echo '</table>';
?>
My model
function get_products($category_id)
{
$this->db->select('*');
$this->db->from('categories c');
$this->db->join('products p', 'c.category_id=p.category_id', 'left');
$this->db->where('c.category_status = 0');
$this->db->where('c.category_id', $category_id);
$query = $this->db->get();
return $query->result_array();
}
function get_price($category_id)
{
$this->db->select('*');
$this->db->from('categories c');
$this->db->join('price r', 'c.category_id=r.category_id', 'c.product_id=r.product_id', 'left');
$this->db->where('c.category_status = 0');
$this->db->where('c.category_id', $category_id);
$query = $this->db->get();
return $query->result_array();
}
How can i join the two arrays from controller?
to iterate over 2 arrays, use array_map
function output_prices($product,$price) {
$n++;
echo '<tr><td>' .$n .'</td><td>'.$product['product_id'].'</a></td>
<td>'.$product['product_name'].'</td><td>'.$product['product_description'].'</td><td>'.$price['price_per_unit'].'</td><td>'.$price['price_per_item'].'</td></tr>';
}
array_map('output_prices',$products,$prices);
source: http://php.net/manual/en/function.array-map.php
Please change your View as per below mentioned code.
<?php
$n=0;
$merg_detls=array_merge($products,$prices);
foreach($merg_detls as $detl) {
$n++;
echo '<tr><td>' .$n .'</td><td>'.$detl['product_id'].'</a></td>
<td>'.$detl['product_name'].'</td><td>'.$detl['product_description'].'</td><td>'.$detl['price_per_unit'].'</td><td>'.$detl['price_per_item'].'</td></tr>';
}
echo '</table>';
?>
Friends I'm Unable to get open positions Sum. here is my code. I am getting 1(one) instead of total sum. Help me to solve this issue.
Controller:
function index(){
$userId = $this->phpsession->get("userId");
$userType = $this->phpsession->get('userType');
$date = date("Y-m-d");
if(!$userId && !$this->phpsession->get("userType")){
redirect(base_url().'user');
}
$config['base_url'] = base_url().'requirement/index';
$config['total_rows'] = $this->requirement_model->GetRequirement(array("count"=>true));
$config['per_page'] = 5;
$config['cur_tag_open'] = '<a>';
$config['cur_tag_close'] = '</a>';
$this->pagination->initialize($config);
$options['offset'] = $this->uri->segment(3);
$options['limit'] = $config['per_page'];
$options['join']=true;
$data['clients'] = $this->client_model->ajaxclient();
$data['requirements'] = array(""=>"Choose requirement");
$data['requirement'] = $this->requirement_model->GetRequirement($options);
$data['links'] = $this->pagination->create_links();
$data['totalactive']=$this->requirement_model->GetRequirement(array("find"=>true));
$data['totalrequirement']=$this->requirement_model->GetRequirement(array("totalreq"=>true));
$data['openpositions']=$this->requirement_model->GetRequirement(array("openpos"=>true));
//print_R($data['openpositions']);exit;
//echo "<pre>"; print_R($this->db->last_query()); exit;
$data['page_title'] = "Requirement Details";
$this->layout->view("requirement/index",$data);
}
This is my model function
Model:
function GetRequirement($options = array()){
if(isset($options['requirementId']))
$this->db->where('requirementId',$options['requirementId']);
if(isset($options['clientName']))
$this->db->where('clientName',$options['clientName']);
if(isset($options['limit']) && isset($options['offset']))
$this->db->limit($options['limit'], $options['offset']);
else if(isset($options['limit']))
$this->db->limit($options['limit']);
$this->db->order_by("activateddate", "DESC");
if(isset($options['join'])){
$this->db->select('r.*,c.clientName as cName');
$this->db->from('requirement as r');
$this->db->join('clients as c','c.clientId=r.clientName');
$query=$this->db->get();
if(#$options['requirementId']) return $query->row(0);
return $query->result();
}
if(isset($options['find'])){
$this->db->select('distinct(clientName)');
$this->db->from('requirement');
$this->db->where('(clientName) and (noofpositions > 0) ');
$this->db->count_all();
$query=$this->db->get();
return $query->num_rows();
}
if(isset($options['totalreq'])){
$this->db->select('requirementName');
$this->db->from('requirement');
$this->db->where('(noofpositions > 0) ');
$this->db->count_all();
$query=$this->db->get();
return $query->num_rows();
}
if(isset($options['openpos'])){
$this->db->select_sum('openPos');
$this->db->from('requirement');
$this->db->where('(closedPos = 0) ');
$this->db->count_all();
$query=$this->db->get();
return $query->num_rows();
}
$query = $this->db->get('requirement');
if(isset($options['count'])) return $query->num_rows();
if(#$options['requirementId']) return $query->row(0);
return $query->result();
}
This is my View page
View:
<div class="inner">
<h3><?php echo $openpositions; ?></h3>
<p>Total Positions Opened</p>
</div>
You are using sum which is an aggregate function and with out group by it will take whole table as one group in if(isset($options['openpos'])){ ... } part of code of your model your are returning num_rows() which returns the no. of rows so in your case there will be one row with the value of sum therefore you are getting result as 1 change your
if (isset($options['openpos'])) {
$this->db->select_sum('openPos');
$this->db->from('requirement');
$this->db->where('(closedPos = 0) ');
$query = $this->db->get();
return $query->row()->openpos;
}
I think the mysql statement has an error.
Change the following line:
$this->db->where('(closedPos = 0) ');
To
$this->db->where('closedPos', 0);
remove the following line: (this will count all rows and return the value, which you do not want)
$this->db->countall();
If this does not solve your problem you could try outputting the mysql statement by adding exit($this->db->last_query()); to try and find the problem, like this:
if(isset($options['openpos'])){
$this->db->select_sum('openPos');
$this->db->from('requirement');
$this->db->where('(closedPos = 0) ');
$this->db->count_all();
$query=$this->db->get();
// output last query
exit($this->db->last_query());
return $query->num_rows();
}
I want to get all query results where I get the id's from another query. I get all relevant id's from both table but i can show only one result in my view. Where is my folt, and how can I fix this?
my Controller:
$results = $this->my_model->hd($query_array ,$limit, $offset);
$data['r']= $results ['rows'];
$data['num_results']= $results ['num_rows'];
$id_str = '';
foreach($results['rows'] as $row){
$id_str .= $row->id . ',';
}
$id_str = rtrim($id_str, '');
$doff = $this->my_model->off($id_str);
$data['o']= $doff ['rows'];
My Model:
function hd($query_array,$limit, $offset){
//result query
$q = $this->db->select('*')
->from('a')
->limit($limit, $offset);
if (strlen($query_array['cy'])){
$q->like('cy', $query_array['cy']);
}
if (strlen($query_array['cat'])){
$q->where('cat', $query_array['cat']);
}
if (strlen($query_array['rat'])){
$q->where('rat', $query_array['rat']);
}
$ret['rows'] = $q->get()->result();
$q = $this->db->select('COUNT(*) as count', FALSE)
->from('r');
if (strlen($query_array['cy'])){
$q->like('cy', $query_array['cy']);
}
if (strlen($query_array['cat'])){
$q->where('cat', $query_array['cat']);
}
if (strlen($query_array['rat'])){
$q->where('rat', $query_array['rat']);
}
$tmp = $q->get()->result();
$ret['num_rows'] = $tmp[0]->count;
return $ret;
}
function off($id_str){
$off_a = $this->db->select('*')
->from('off')
->where('r_id', $id_str);
$ret['rows'] = $off_a->get()->result();
return $ret;
}
I show in my view the result in a foreach loop. I tried to fix this problem since three days by my self and google, but no luck.