Join does not work - php

I have write a function using SQL join but i do not know why it does not work
this is a model
public function get_contract_user($user_id)
{
$this->db->select('contracts.*');
$this->db->from('contracts');
$this->db->join('link', 'contracts.contract_id = link.contracts_contract_id');
$this->db->where('link.users_user_id', $user_id);
$query = $this->db->get();
return $query->result();
}
this is the app
$data['query'] = $this->admin_model->get_contract_user($contract_id);
this is a view
foreach($query as $row)
{
echo $row->contract_code;
echo $row->contract_num;
echo $row->contract_start;
echo $row->contract_end;
}

You defined method get_contract_user, but you are using get_contract in provided code.
You should be getting an error concerning undefined function/method.

Related

How to get users list in codeigniter?

I am trying to get list of users from Users table in codeigniter. My problem is that if am using following code than try to print out the result, it's giving me blank array while printing query using last_query() function and running this query in phpmyadmin is giving correct result.
My code in model
$data = $this->db->select('u.*')
->from('users u')
->join('users_groups ug','ug.user_id = u.id')
->join('groups g','g.id = ug.group_id')
->where('g.id',7)
->get()
->result();
this code is giving me blank array then what i did is print the query using following code
echo $this->db->last_query();
and this is what query was
SELECT `u`.* FROM `users` `u` JOIN `users_groups` `ug` ON `ug`.`user_id` = `u`.`id` JOIN `groups` `g` ON `g`.`id` = `ug`.`group_id` WHERE `g`.`id` = 7
which is working fine. but i am trying to print the data using print_r($data)
is giving me blank array.
Can anyone tell me what can be the issue ?
edited
My full model code.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Technician_model extends CI_Model {
public function _consruct(){
parent::_construct();
}
function getData(){
$data = $this->db->select('u.*')
->from('users u')
->join('users_groups ug','ug.user_id = u.id')
->join('groups g','g.id = ug.group_id')
->where('g.id',7)
->get()
->result();
return $data;
}
function getRecord($user_id){
$record = $this->db->get_where('users',array('id'=>$user_id))->row();
echo '<pre>';
print_r($record);
exit;
return $record;
}
function addModel($data){
if($this->db->insert('users',$data)){
return $this->db->insert_id();
}
else{
return FALSE;
}
}
function editModel($data,$user_id){
$this->db->where('id',$user_id);
if($this->db->update('users',$data)){
return true;
}
else{
return false;
}
}
function deleteModel($user_id){
$this->db->where('id', $user_id);
if($this->db->delete('users')){
return true;
}
else{
return FALSE;
}
}
}
?>
You may try this simple way to join table. you may try this and can
change fields name table name and method according to your
require.
public function getUser() {
$this->db->select('users');
$this->db->from('Users');
$this->db->where('users_groups.user_id',1);
$this->db->join('users_groups', 'users.id = users_groups.user_id');
$query = $this->db->get();
$result = $query->result_array();
var_dump($result); // display data in array();
return $result;
}
Actually, at the end of 2 hrs of the journey, I found that I forgot to configure new database.
All the answers were correct in this case.

i want to display value from database in codeigniter but i am getting errror

I want to display a value in view in CodeIgniter but I am getting several errors like trying to get the property on non-object. I think my code is correct but I am getting errors. Below is my code.
controller:
public function trainer($id)
{
$user_record = $this->db->query("select * from usr_data where usr_id=$id")->result();
$data['title'] = 'trainer Dashboard';
$data['user_record'] = null;
$data['active_courses'] = [];
$data['inprogress'] = [];
if(count($user_record)) {
$user_record = $user_record[0];
$data['title'] = ucwords($user_record->firstname).' Dashboard';
$data['user_record'] = $user_record;
$active_courses = $this->base_model->getTrainercourseAll($id);
$data['active_courses'] = $active_courses;
$inprogress = $this->base_model->getstaffinprogress($id);
$data['inprogress'] = $inprogress;
}
$this->load->view('trainer-dashboard', $data);
}
model:
public function getstaffinprogress($user_id) {
$result=$this->executeSelectQuery("select AVG(m.percentage) from object_data o, ut_lp_marks m where o.obj_id=m.obj_id and o.type='crs' and m.status=1 ");
return $result;
}
view:
<h3>Avg inprogress:<?php echo "<span style='color:#ff00ff;font-family:verdana;'>".$inprogress->percentage."</span>";?></h3>
I want to display the column percentage which is coming from database.above code is in the controller, model and view.i thought my controller code is wrong.
Anyone help me to get rid of this error. I want to display a value in view in CodeIgniter but I am getting several errors like trying to get the property on non-object. I think my code is correct but I am getting errors. Below is my code.
Try this in your view file,
if(isset($inprogress)){
echo $inprogress->percentage;
}
Then your code look like this,
<h3>Avg inprogress:<?php if(isset($inprogress)){ echo "<span style='color:#ff00ff;font-family:verdana;'>".$inprogress->percentage."</span>";}?></h3>
Then call the controller function. I think inprogress is not set at the first time.
If it doesn't work, try to var_dump($inprogress) in controller and check value and type.
And try this code in your model. Query also seems not correct
public function getstaffinprogress($user_id) {
$this->db->select_avg('ut_lp_marks.percentage');
$this->db->where('ut_lp_marks.obj_id', $user_id);
$this->db->where('object_data.type', 'crs');
$this->db->where('ut_lp_marks.status', 1);
$this->db->join('object_data', 'object_data.obj_id = ut_lp_marks.obj_id');
$query = $this->db->get('ut_lp_marks');
return $query->result_array();
}
I assume that your db is ut_lp_marks. Then var_dump array and check data is correct first. Then access array element.
public function getstaffinprogress($user_id) {
$result = array();
$query=$this->db->query("select AVG(m.percentage) from object_data o, ut_lp_marks m where o.obj_id=m.obj_id and o.type='crs' and m.status=1 ");
foreach($query->result() as $row){
$result = $row;
}
return $result;
}
Also check $inprogress->percentage exists before print in view.

I need to call a controller function inside a view -Codeigniter

I need to call a function from view to echo a value. I use following code,
Controller (test_controller)
public function displayCategory()
{
$this->load->model('Model_test');
$data['categories'] = $this->Model_test->getCategories();
$this->load->view('test_view', $data);
}
public function display($id)
{
$this->load->model('Model_test');
$name= $this->Model_test->getName($id);
return $name;
}
Model (Model_test)
function getCategories() {
$query = $this->db->query("SELECT * FROM category");
if ($query->num_rows() > 0) {
return $query->result();
} else {
return NULL;
}
}
function getName($userId) {
$query = $this->db->query("SELECT name FROM user where id = '$userId' ");
if ($query->num_rows() > 0) {
return $query->row()->name;
} else {
return NULL;
}
}
View
<div id="body">
<?php
foreach ($categories as $object) {
$temp = $this->test_controller->display($object->id);
echo $object->title . " ". $object->no . $temp . '<br/>';
}
?>
</div>
but some error when running the code.
error Message: Undefined property: CI_Loader::$test_controller in view
I am not sure if you use CodeIgniter 2 or 3.
Anyway, basically you don't want to use anything inside View files except perhaps helper function(s) or some kind of "presenter" layer (that should be called inside controller I guess).
Solution using Join
Go and read this manual page and search for join. There you can learn about implementation of SQL join directive.
You want to modify this (getCategories()) function so it returns data that you require
function getCategories() {
$this->db->select('category.title, category.no, user.name as username')
->from('category')
->join('user', 'user.id = category.id');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return NULL;
}
}
and in view you can get your username like this
foreach ($categories as $object) {
echo $object->title . " ". $object->no . $object->username . '<br/>';
}
I am not 100% sure so please post comments I will edit this answer later.
Solution "breaking rules"
https://stackoverflow.com/a/24320884/1564365
general notes
Also consider naming your tables using plural so categories, users...
Also it is a bad practise to use "category.id as user.id" (storing user id inside category table in "id" field) instead you shold use either a pivot table or in case of 1:1 relation field "user_id".

Codeigniter php MVC

I have a table called 'News' with three columns: 'id', 'title' and 'details'
I have a function ('get_entry') inside a codeigniter model class (called 'News_model')
function get_entry()
{
$this->load->database();
return $this->db->select('id,title,details')->from ('news');
$data['newsarray'] = $this->db->row_array();
return $data['newsarray'];
}
I am connecting to the db so that is not the problem.I want to return an iterable array from get_entry() by calling the function from a controller file with the followlwing code. I want to push it into another array (called '$data['theNews']') using the code below.
foreach ($this->News_model->get_entry() as $key => $value){
array_push($data['theNews'],$value->title);
}
I have been using the code on this (https://www.codeigniter.com/user_guide/general/models.html) as a template (in particular the function 'get_last_ten_entries()' but I think I am close with the code I posted above. I would appreciate any help.
About your code:
You have two 'return' in your get_entry function:
function get_entry()
{
$this->load->database();
// First
return $this->db->select('id,title,details')->from ('news');
$data['newsarray'] = $this->db->row_array();
// Second
return $data['newsarray'];
}
Change it to:
function get_entry()
{
$this->load->database();
$query = $this->db->select('id,title,details')->from('news');
$data['newsarray'] = $query->row_array();
return $data['newsarray'];
}
It should work now.
Some advices:
Don't use Codeigniter 2 anymore. Version 3 is alive.
If you plan to return whole table columns, i suggest you to use the following code for the query:
$query = $this->db->get('news', 1, 20);
Where 1, 20 is the limit.
Now you can get the result:
return $query->result();
A simple example:
function get_entry()
{
$this->load->database();
$query = $this->db->get('news', 1, 20);
return $query->result();
}
This method returns the query result as an array of objects that you can print like so in your controller:
$news_array = $this->News_model->get_entry();
foreach ($news_array as $news)
{
echo $news->id;
}
Look at CI 3 Query Builder query builder for more examples.
One more suggestion, just autoload the database library in application/config/autoload.php if you need it globally.
Changing the code to this in the function worked:
function get_entry()
{
$this->load->database();
$query = $this->db->get('news');
//return $query->result();
foreach ($query->result() as $row)
{
echo "</br>";
echo $row->id;
echo "</br>";
echo $row->title;
echo "</br>";
echo $row->details;
echo "</br>";
}
}
Calling the function like so prints it out:
$news_array = $this->News_model->get_entry();

codeigniter use part of query result in another query

It was hard to come up with a title. I am using CodeIgniter with models/views/controller. I have the following tables in my MySQL database that are relevant:
In my model I have the following function:
function get_shoptable() {
$this->db->from('productshop')->where('productId', $this->productId);
$query = $this->db->get();
return $query->result();
}
In my controller I use the above function like
$data['bookshop'] = $this->Product_model->get_shoptable();
In my view I am foreaching $bookshop. My problem is, what is the best wayto show shopName, instead of showing shopId. Taking in regards that $bookshop should be as it is (except of shopid), because I am creating a HTML table with product data.
Try some like this:
function get_shoptable() {
$this->db->from('productshop')
->join('shop', 'productshop.shopId = shop.shopId')
->where('productshop.productId', $this->productId);
$query = $this->db->get();
return $query->result();
}
Model:
function get_products() {
$this->db->select('productshop.productUrl, productshop.price, productshop.deliveryTime, productshop.shippingCast, productshop.inventory, productshop.productId, productshop.shopId, shop.shopName');
$this->db->from('productshop');
$this->db->join('shop', 'productshop.shopId = shop.shopId');
$this->db->where('productshop.productId', $this->productId);
return $this->db->get()->result_array();
}
Controller:
function products() {
$data['products'] = $this->model_name->get_product();
$this->load->view('products', $data);
}
VIEW:
<?php foreach($products as $p): ?>
<h1><?php echo $p['productUrl']; ?></h1>
<h1><?php echo $p['shopName']; ?></h1>
<?php endforeach(); ?>
get an overlook to active class of codeigniter for details of functions
function get_shoptable()
{
$this->db->from('productshop')
$this->db->join('shop', 'productshop.shopId = shop.shopId')
$this->db->where('productshop.productId', $this->productId);
$query = $this->db->get();
return $query->result();
}

Categories