URI's to fetch database data (CodeIgniter) - php

So I'm trying to utilise CodeIgniter's URI segment functionality. I have the URI segments being used as ids to retrieve information from the database.
It's working fine, but I have noticed that if I put in an id that doesn't exist in the database, it spits out a database error.
How do I prevent this from happening?
Model Code:
$query = $this->db->select('*')
->from('questions')
->where('questions.id', $question_id)
->join('users', 'users.id = questions.user_id')
->get();
return $query->row();
Call to model in controller:
$question_id = $this->uri->segment(3);
$data['question'] = $this->forum_model->get_question($question_id);
PHP error:
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object

You need to check if the query returned any results before calling $query->row
The way to do it is:
$query = $this->db->select('*')
->from('questions')
->where('questions.id', $question_id)
->join('users', 'users.id = questions.user_id')
->get();
if($query->num_rows() > 0)
return $query->row();
else
return false;
$query->num_rows() will give you the number of rows returned.

to debug just do this...
//if this gives u no result, then thats the problem because it couldnt find the
//$this->uri->segment(3);
$question_id = $this->uri->segment(3);
echo $question_id;
//if this prints out the expected result.
//then you should know that the problem is still somewhere down the code.
$data['question'] = $this->forum_model->get_question($question_id);
var_dump($data['question']);
//this is for your model.
echo $question_id
$query = $this->db->select('*')
->from('questions')
->where('questions.id', $question_id)
->join('users', 'users.id = questions.user_id')
->get();
return $query->row();
NOTE: if all this echos outputs valid values, then check somewhere else for the problem

Related

LARAVEL: How to fetch id dynamically in a query builder?

I want to join multiple tables in laravel with query builder. My problem is that my code only works if I specify the id myself that I want like this:
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=','1')
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
But I would want something like this(which I just can't seem to figure out)
public function showuser($id)
{
$userid = User::findOrFail($id);
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$userid)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
}
Am I making a syntax mistake? When I check the page for my json response in second page it just returns empty brackets, but when I specify the id it fetches me the right data
The findOrFail method will return the entire user model, with all its properties, since you already have the user id. You dont need to get the entire user model for that, you could just use the $id you receveid as a parameter like this:
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$id)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
public function showuser($id)
{
$getUserByID = User::findOrFail($id); //not used
$userData = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$id)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($userData);
}
But the best way is to have relations set on models
public function showuser($id)
{
$userData = User::where('id', $id)->with(['activitates','taga_cars','clients'])->first();
return response()->json($userData);
}

how to read a specific field from an array returned by the model in the controller itself

I have a function in the controller "thisTopic" that has following:
$viewdata = array();
$viewdata['reply'] = $this->disc->get_all_replies($topic_id);
$viewdata['firstReply']= $this->disc->get_firstReply();
In the model:
public function get_all_replies($topic_id){
return $results = $this->db->select('*')
->from('disc_replies')
->join('users', 'users.id = disc_replies.users_id')
->where('topic_id',$topic_id)
->get()->result();
}
public function get_firstReply($reply_id){
return $results = $this->db->select('*')
->from('disc_firstReply')
->join('users', 'users.id = disc_firstReply.users_id')
->where('reply_id',$reply_id)
->get()->result();
}
The disc_replies table has the following columns:
1. reply_id
2. topic_id
3. users_id
4. replied_on
from the $viewdata['reply'] I want to read the reply_id field of the first row and sent it as the parameter to the get_firstReply() function.
This is what I tried so far:
$viewdata['firstReply']= $this->disc->get_firstReply($viewdata['reply'][0]['reply_id']);
$viewdata['firstReply']= $this->disc->get_firstReply($viewdata['reply']['reply_id']);
But nothing works, any help to solve this problem is really appreciated. Thanks in advance
In order to use this $viewdata['reply'][0] (0 pointed array) in codeigniter, You have to format array as objective array.
This
->get()->result();
should change as
->get()->result_array();
You can check the format of the array by using this print_r($viewdata['reply'])
Make sure $viewdata['reply'] is not empty

Laravel Join Returning odd values

Just come across a bug on my Join query.
I am echoing out data in a foreach, and showing the username. On other pages it works fine and each username matches the username from the ID in the row. However, in the example below the username return is ALWAYS the name of the logged in user.
Hope the below makes some more sense. Thanks.
The query is:
$query = DB::table('blogs')
->join('followers', 'blogs.id', '=', 'followers.blogid')
->where('followers.userid', Auth::user()->id)
->where('frontpage', '1')
->latest('lastupdated');
This is called via:
Route::get('following', array('before' => 'auth', function()
{
$slug = Route::getCurrentRoute()->uri();
$builds = Blog::findBuilds($slug);
return View::make('pages/home', compact('builds'), array('pageTitle' => 'Builds You Are Following'));
}));
And then on the pages/home I am showing the data like so:
foreach ($builds as $build)
{
$usernameOfOwner = User::usernameFromID($build->userid);
}
And then... the function for getting the username from ID is:
public static function usernameFromID($id) {
$user = DB::table('users')->where('id', $id)->first();
return $user->username;
}
Everywhere else on my website when I run a query similiar to the top one but not a join so e.g.:
$query = static::where('frontpage', '1')->latest('lastupdated');
It works fine, so my only guess is that its down to the Join as thats the only different part of the code.
The problem is that you have multiple columns named userid. followers.userid and blogs.userid. Now in this case, unfortunately followers.userid gets returned when you use $build->userid
You can change that by only selecting the columns you want in your result.
$userid = Auth::user()->id;
$query = DB::table('blogs')
->join('followers', function($q) use ($userid){
$q->on('blogs.id', '=', 'followers.blogid');
$q->where('followers.userid', '=', $userid);
})
->select('blogs.userid', 'other-column')
->where('frontpage', '1')
->latest('lastupdated');
By the way: * works too, so you can do select('blogs.*') if you want

Codeigniter activerecord query continuously runs

When I try to run the follow query it never returns anything, it just keeps running. What am I doing wrong with it?
$this->db->distinct('customer.Name')
->from('customer')
->from('invoicelinedetail')
->from('invoice')
->from('iteminventory')
->where('invoice.CustomerRef_ListID = customer.ListID')
->where('invoicelinedetail.IDKEY = invoice.TxnID')
->where('invoicelinedetail.ItemRef_ListID =', $id)
->order_by('customer.Name', 'desc');
$query = $this->db->get();
After $this->db->get(); you need to retrieve your results
More info from CI Docs
To do this, set $query= to one of the following:
$this->db->result_array(); //returns array
$this->db->row_array(); //returns single row as array
$this->db->result(); //returns object
$this->db->row(); //returns single row as object

request in PhpMyAdmin works, with Laravel Query Builder, doesn't seem to work

I have a problem that I can't fix :
this request works in PHPMYADMIN
SELECT cronState.name, command.name, parameter.keyword, eventParameterValue.value
FROM cronState, commandInstance, command, eventParameterValue, parameter
WHERE cronState.id = commandInstance.cronState_id
AND commandInstance.command_id = command.id
AND eventParameterValue.commandInstance_id = commandInstance.id
AND eventParameterValue.parameter_id = parameter.id
AND cronState.id =32
it returns :
name name keyword value
on20 DigitalPinSet State 1
on20 PwmPinSet DutyCycle 20
and it's ALL I want.
LITTLE EDIT : I use an AJAX Request(with a state_name) to this method which should returns the query result.
Now, when I try to implement it with the Laravel Query Builder, it returns some errors.
My code:
$cronState_id = DB::table('cronState')
->where('name', Input::get('state_name'))
->first();
$cronEvent = DB::table('cronState')
->join('commandInstance', 'commandInstance.cronState_id', '=', 'cronState.id')
->join('command', 'commandInstance.command_id', '=', 'command.id')
->join('eventParameterValue', 'eventParameterValue.commandInstance_id', '=', 'commandInstance.id')
->join('eventParameterValue', 'eventParameterValue.parameter_id', '=', 'parameter.id')
->where('cronState.id', '=', $cronState_id->id)
->select('cronState.name', 'command.name', 'parameter.keyword', 'eventParameterValue.value');
foreach($cronEvent as $result){
$ev = $result['keyword'];
}
return $ev;
The error for this code :
{"error":{"type":"ErrorException","message":"Undefined index:
keyword","file":"/var/www/stage/app/controllers/EventController.php","line":48}}
if I change
foreach($cronEvent as $result){
$ev = $result['keyword'];
}
return $ev;
to
return $cronEvent;
(just delete the foreach loop and rename the returning variable), I have this error :
{"error":{"type":"ErrorException","message":"Object of class
Illuminate\Database\Query\Builder could not be converted to
string","file":"/var/www/stage/vendor/symfony/http-foundation/Symfony/Component/HttpFoundation/Response.php","line":361}}
So, how can access to my data in the object ? Maybe my Query Builder implementation doesn't works...
Thanks for any help !
There is missing get() at the end of that query builder, thus you don't run the query at all. That's it.

Categories