Codeigniter DB with slug - php

I'm in trouble when trying to get DB data passing slug in URL.
public function news($slug = "")
{
$query = $this->db->get_where('news', array("slug", $slug));
$row = $query->row_array();
}
If i try to 'echo' information, e.g echo $row["message"]; I see blank page. =/
What I'm doing wrong?

$query = $this->db->get('news', array("slug", $slug))->row_array();
or
$query = $this->db->where( "slug", $slug)->get('news')->row_array();
var_dump($query);

in my nsh opinion this is not a good idea
public function news($slug = "")
the only way its acceptable to say that the method parameter can be blank is if the method still works without it. which in this case it won't.
anyway lets write this out
// the fields you want
$this->db->select( 'id,and,oh,here,are,some,fields' );
// the where condition
$this->db->where( 'slug', $slug);
// the table name and create the query
$query = $this->db->get( 'news' );
now before sending $query out into the world, make sure it has a record for you by using num_rows()
if ( $query->num_rows() == 1 ) { return $query->row_array(); }
// so you also have the option to check for and return a group of records
// but the rules this time are one article only, so return false
else{ return false ; }
now in your controller, assuming your model is called something like articles, do it something like this
$slug = 'something that has already been validated' ;
// if no article came back, do something else
if( ! $article = $this->articles->news($slug) )
{
// no article came back
// show appropriate view
$this->_showNoArticleFor($slug) ;
}
else{ $this->_showFound($article) ; }
in codeigniter an underscore in the controller method names automatically makes them private so they can't be accessed publicly. in general if a form or search fails - call a separate method that clearly states that something has not been found or its failed. that way you keep your views separate because views change often. otherwise you are piling completely different types of view files inside if conditions and its a mess.

Related

Query in Yi2 and checking a relationship in another table

I am trying to get data in a Yii2 table call Post. This table has an attribute call owner and I want to check whether the value of owner is equal to a particular Value I pass call it userId or the value of owner is equal to the following attribute of the Followship table where the value of the follower attribute of the Followship Table is equal to the the value I pass call it userId.
In implementing the above logically and bit by bit, I have written the following code;
$allpost = Post::find()->all();
$relevantpost = [];
foreach ($allpost as $post) {
if($post->owner == $userId){
$relevantpost[] = $post;
}
else{
$follower = Followship::findOne(['follower'=>$userId, 'following'=>$post->owner]);
if($follower){
$relevantpost[] = $post;
}
}
}
return $relevantpost;
This code works well but I want to write an active query for this such as ;
$allpost = Post::find()
->where(['owner'=>$userId])
->orWhere(['is NOT', $follower = Followship::findOne(['follower'=>$userId]) and 'owner' => $follower->following, NULL])
->all();
or in the worse case,
$allpost = \Yii::$app->db
->createCommand(
"SELECT postId, location, details, created_at FROM Post
WHERE owner = " . $userId. "OR
owner = '0' OR
owner = following IN (
SELECT following FROM Followship WHERE follower = ". $userId . " AND
)
ORDER BY dateCreated DESC"
)
->queryAll();
I keep getting errors with the above queries. I am missing out a fundamental of the Yii2 query builders.
Please any help on this will be greatly appreciated.
First you could make a relation (which connects Post and Followers by post owner) inside your Post class
class Post extends ActiveRecord {
public function getFollowersDataset() {
return $this->hasMany(Followers::className(), ['following' => 'owner']);
}
...
}
And then you can just use it in your queries
Post::find()
->joinWith('followersDataset')
->where(['or',
['owner' => $user_id],
['follower' => $user_id]])
->all()
The condition accept three parameters
[the_condition, the_attribute, the_value]
In case of AND and OR the thing change
[the_condition, first_condition, second_condition]
With the second tried you can make something like that
$allpost = Post::find()
->where(['owner'=>$userId])
->orWhere([
'AND',
['is NOT', $follower, Followship::findOne(['follower'=>$userId]),
['owner', $follower->following, NULL]
])
->all();
You can check in debug bar the querys that you're making, or another way, its to make a mistake in a field, for example if in your where condition you put ->where(['owners'=>$userId]), that trhow an error with the query that you made, so you can see what query you did

Laravel trying to check if the user has relationship with post

I have posts and these posts can be saved by users to read later. I created this relation and I can save or delete them easily. The problem is I can't check if the post is saved or not in frontend. Now I wrote some code to handle this but it doesn't seem to work. here is my controller code:
$articleFlag = 1;
$userID = Auth::User()->id;
if (count($bestarticles) > 0) {
foreach ($bestarticles as $bestarticle) {
$saveddata = DB::table('savearticle')->where('user_id', $userID && 'article_id', $bestarticle);
if (count($saveddata) > 0) {
$articleFlag = 1;
} else {
$articleFlag = 2;
}
} //foeach endes here
} //first if endes here
and than I pass the $articleFlag to the view than checking it's value with an if
But the problem is, no matter what I do if (count($bestarticles) > 0) returns true and I get value 1 in view.
Does anybody have any idea what I might be missing?
Here is my user controller relationshio:
function savedarticle(){
return $this->belongsToMany('App\User', 'savearticle', 'user_id',
'article_id');
}
and here goes the functions that i use for saving and deleting:
function savethearticle(Article $article){
$this->savedarticle()->syncWithoutDetaching([$article->id]);
}
function removethearticle(Article $article){
$this->savedarticle()->detach([$article->id]);
}
But there is nothing you need to worry about. I'm able to delete and add.
Or is there another way to check for existing relationship in view or a better way to check it in controller and pass into view?
I am using Laravel 5.4.
It looks as though you have a Collection of Article models, and you're trying to determine whether it is related to the User or not.
If that's the case, I would suggest eager loading the User relation when you originally query the Article models. This has the advantage of using one query to load the relationship, rather than one per Article.
$userId = Auth::id();
$articles = Article::with(['savedarticle' => function ($query) use ($userId) {
return $query->where('user_id' => $userId);
}])->get();
With this Collection, because we have loaded specifically the currently authenticated User, you can then proceed knowing that if the savedarticle relation has a count of 1, that the User relation exists.
foreach ($articles as $article) {
if ($article->savedarticle->count()) {
// User has already saved article
} else {
// User has not saved article
}
}
Should you not be passing the id of bestarticle in the Where clause? Also, it requires a ->get() to actually fire the request off to the database and run the query.
$saveddata = DB::table('savearticle')->where('user_id', $userID && 'article_id', $bestarticle);
Should be
$saveddata = DB::table('savearticle')->where('user_id', $userID && 'article_id', $bestarticle->id)->get();

Only last row getting displayed in view in Codeigniter

I'm trying to fetch certain values from and then pass it to another model in the same control.
However I'm only able to display the last row in the view.
I have shared my code below and I'm not sure where I'm going wrong.
Controller:
public function test($id){
$mapping_details = $this->queue_model->get_mapping_details($id);
foreach ($mapping_details as $value) {
$data['agent_details'] = array($this->agent_model->get_agent_details($value['user_id']));
}
$this->load->view('app/admin_console/agent_queue_mapping_view', $data);
}
Model:
public function get_agent_details($id) {
$query = "select * from user_table where id = ".$id." and company_id = ".$this->session->userdata('user_comp_id');
$res = $this->db->query($query);
return $res->result_array();
}
Welcome to StackOverflow. The problem is the iteration in your controller. You are iterating through the $mapping_details results and per every iteration you are re-assigning the value to $data['agent_details'] , thus losing the last stored information. What you need to do is push to an array, like this:
foreach ($mapping_details as $value) {
$data['agent_details'][] = $this->agent_model->get_agent_details($value['user_id']);
}
However, wouldn't it be best if you created a query that uses JOIN to get the related information from the database? This will be a more efficient way of creating your query, and will stop you from iterating and calling that get_agent_details() over and over again. Think of speed. To do this, you would create a model method that looks something like this (this is just an example):
public function get_mapping_details_with_users($id){
$this->db->select('*');
$this->db->from('mapping_details_table as m');
$this->db->join('user_table as u', 'u.id=m.user_id');
$this->db->where('m.id', $id);
$this->db->where('u.company_id', $this->session->userdata('user_comp_id'));
return $this->db->get()->result();
}
Then your controller will only need to get that model result and send it to the view:
public function test($id){
$data['details_w_users'] = $this->queue_model->get_mapping_details_with_users($id);
$this->load->view('app/admin_console/agent_queue_mapping_view', $data);
}
Hope this helps. :)

method to find actually data deleted or not in database in codeigniter [duplicate]

This question already has answers here:
How can I detect a create, update, delete query is successful in Codeigniter
(2 answers)
Closed 2 years ago.
Hi every is there any way to check whether data is actually deleted from database or not in codeigniter ?
i have a method to delete data from database in my model as
$this->db->delete('product', array('category' => $id));
and i have set flash datain my controller
the data from database doesn't gets deleted but the flash message is shown.
I need to show flash data only on actual delete from database.
i prefer this
in model for example called 'products'
function deleteProductBy( $id ) {
$this->db->where( 'category', $id );
$this->db->delete( 'product' );
if ( $this->db->affected_rows() == '1' ) {return TRUE;}
else {return FALSE;}
}
in controller
if( $this->products->deleteProductBy($id) == false ){
// fail message is sad
}
else{
// success message is happy
}
so have the delete method in the model just return true or false -- then in the controller you decide how you are going to show the results. then when something changes for how you show the results - the delete method in the model remains the same. and while i'm rambling my suggestion is to check for false condition first.
Try this:
if($this->db->delete('product', array('category' => $id))) // This will return TRUE if deleted and return FALSE if it couldn't delete the row.
If that doesn't work i'd suggest using something like this:
$this->db->delete('product', array('category' => $id));
if ($this->db->affected_rows() > 0) // affected_rows will return you the number of affected rows, so if you delete one it will return 1.
{
// show flash message
}
After deleting the data in table, write a select query for that category id. If count is zero then there will be no record with that category id. else there will be some date with that id. i.e, Not deleted.
For example,
function deleterecord(){
$this->db->delete('product', array('category' => $id));
//return TRUE or redirect to controller.
}
//after the above executed call the below function.
function findrecord(){
$query = $this->db->get_where('product', array('category' => $id));
if($query -> num_rows() == 0){
$str ="There is no data";
return $str;
}
else{
$str ="There is data";
return $str;
}
}
You can print the function return value to find result.

How do I retrieve data in INT form from a database with codeigniter?

I am trying to create an update function that adds an entered value to the value for the user in a database. (It adds accounts that can be used for a class to a teacher) So far, I have a test button that should add one account when it's clicked and then refresh the page.
Here is my function thus far:
public function add_account()
{
$this->load->model("teacher_data_model");
$user = $this->ion_auth->user()->row();
$user_id = $user->id;
$data = array(
'user_id' => $user_id,
'unused_accounts' => [what do I insert here?]
);
$this->teacher_data_model->add_accounts($data, $user_id);
redirect('teacher', 'refresh');
}
This function is admittedly sloppy, I am still fairly new to this. This function gets the user ID and passes it to a model that uses it to find our teacher and update the number of student accounts they have. So far this works as long as I have a fixed value for 'unused_accounts', the problem is when I do this:
public function add_account()
{
// Getter of the user data
$user = $this->ion_auth->user()->row();
$user_id = $user->id;
$this->load->model("teacher_data_model");
//This gets the existing accounts
$num_accounts["record"] = $this->teacher_data_model->get_unused_accounts($user_id);
$this->load->view("teacher/teacher_data_viewer", $num_accounts);
$data = array(
'user_id' => $user_id,
'unused_accounts' => [what do I insert here?]
);
// data insertion
$this->teacher_data_model->add_accounts($data, $user_id);
redirect('teacher', 'refresh');
}
I'm not sure whether to but the +1 increment in the controller or the model, but I can't even seem to identify the searched data as an int at this point.
For [what do I insert here?] if I use $num_accounts I get this database error:
Error Number: 1054
Unknown column 'Array' in 'field list'
UPDATE teachers SET user_id = '1', unused_accounts = Array WHERE user_id = '1'
Here is my model in case it's needed:
function add_accounts($data, $uid)
{
$this->db->where('user_id', $uid);
$this->db->update('teachers',$data);
}
EDIT: This is my function that gets the data from the database
function get_unused_accounts($usersid)
{
$this->db->select('unused_accounts');
$this->db->from('teachers');
$this->db->where('user_id', $usersid);
$query = $this->db->get();
return $query->result();
}
I'm not sure if this puts out data in INT form. When I was using this to check if the user has at least one account, it always accepts as true even if the user has zero accounts.
I would suggest using raw SQL in your model for this purpose:
function add_accounts($uid, $quantity = 1)
{
$this->db->query('
UPDATE teachers
SET unused_accounts=unused_accounts+'.$quantity.'
WHERE user_id='.$uid
);
}
Now you can increment unused_accounts value by one for a user using
$this->teacher_data_model->add_accounts($user_id);
or by any amount you want using
$this->teacher_data_model->add_accounts($user_id, $amount);
Not sure if CodeIgniter's ActiveRecord would accept statement unused_accounts=unused_accounts+'.$quantity.', but if it does, you can try using this in your controller it wont work, see below for an edited part:
$data = array(
'user_id' => $user_id,
'unused_accounts' => 'unused_accounts + '.$amount
);
EDIT: Looks like if you want to use ActiveRecord, you must use $this->db->set() with a third parameter set to FALSE, so something like this in your model:
function add_accounts($unused_accounts, $uid, $amount = 1)
{
$this->db->where('user_id', $uid);
$this->db->set('unused_accounts', 'unused_accounts+'.$amount, FALSE);
$this->db->update('teachers');
}
Cant answer comments yet but
if($remaining_accounts = 1)
Will allways be true, try:
if($remaining_accounts == 1)
See PHP manual for comparison operators

Categories