Best way to query in CodeIgniter - php

I tried to look for an answer of this but I have a question about filtering with codeigniter. The code below checks if the administrator is logged in shows every idea(brain) status in the query, which could be public or hidden, otherwise, it only shows the ones with public status.
I want to change this to keep showing the ideas with public status to everyone and only the ideas with hidden status of the person that is logged in.
if($this->ion_auth->is_admin()) {
$brain_status = null;
}
else {
$brain_status = $brain::PUBLIC_STATUS;
}
$brain_collection = $this->em->getRepository('Entities\Brain')
->getListPerPage($brain::BRAIN_PER_PAGE, $page, $brain_status);
I tried using
$this->session->user_id and I don't know how many other syntaxes and I can't get it to work, every idea has a field in the database where the user_id is logged when the idea is created to accomplish this.
Any help is extremely appreciated

to complete this Q/A pair, I'm transforming my comments into an answer:
the requirement:
admin sees all ideas: public and hidden, regular user only sees public ideas
the solution:
create a database column "published", associated to each idea (and consequently user_id). Now you can show in your view all records which match published=1 to everyone and those published=0 only to whom where user_id matches (or admins).
If a user is logged-in (you set a session with their user_id) and if this user_id matches the user_id of the idea then you show it. It has the advantage that you could implement for a user to be able to publish or un-publish their own idea, without admin intervention, only viewable to themselves, unless published by admin.

Related

How to keep logs of your users in Laravel 4?

I have users table in my database lay out like this :
id
username
firstname
lastname
email
photo
As of now, since I am an Admin user so I have Admin right, and I can Create, Update, and Delete.
I want to allow all my users to have the same right as me later on.
Before I release this feature, I want to keep track on who edit what - so things doesn't get lost, and it's good to keep the history of things.
What is best practice for this feature ?
I know that I have do some programming logic in my update function in my Controller function.
I know that I have to create a logs table on my database to store
user_id : who make a change
created_at : when the change was made
old_data: string
new_data: string
For someone, that had any experiences with this feature, can you PLEASE give me some advice ?
I really appreciate your concern. Thank You.
I think best approach to this problem is each action that a user takes that you want to log should also fire an event.
Event::fire('some.event', array(Auth::user()));
Then you can register listeners for each event and log appropriately.
Event::listen('some.event', function($user)
{
// create new item in logs table here.
});

Getting Additional Field From Different Table

I saw the following post and I'm trying to use it in a way for my queries however I'm using two different tables.
I have my logins table which uses the logins_model and I have the users table.
Inside of the logins table it only includes login information needed to log the user in.
I currently have the email address as the way for the user to login with the password field.
In my users table it includes all the personal information about the user.
What I am wanting to do is when the user logs in successfully, they are sent to the control panel where I query the database for users table for their personal information to display, however I also need the email address to display.
I'm trying to figure out how I can gather that email address field when I do the initial query.
Here is the GitHub repo for MY_Model from Jamie Rumbelow.
Does anybody have any suggestions on this? I would certainly appreciate it.
I'm hoping someone else can shed some additional insight that has working knowledge of the MY_Model.
I've still been battling this all day and would like any other suggestions that anybody will suggest.
EDIT :
I've found out that I can can make an additional function however it only puts the email address field into the object instead of the email address with the data from the users table. Is there something I"m doing wrong.
$user_data = $this->user->with_email_address()->get_by('user_id', $user_id);
public function with_email_address()
{
$this->db->join('logins', 'logins.user_id = users.user_id');
$this->db->select('logins.email_address AS email_address');
return $this;
}
If you are going to provide a function in the model to return all the information with the email address, you must select all the fields for the JOIN.
Try this:
public function with_email_address($user_id)
{
$this->db->join('logins', 'logins.user_id = users.user_id');
$this->db->select('users.*');
$this->db->select('logins.email_address AS email_address');
return parent::get_by('user_id', $user_id);
}
Instead of querying your other table, you can save the users email address in a session variable when the user logs in. This way you won't need to query your database multiple times for just one variable.
Here you can find additional information about sessions:
http://ellislab.com/codeigniter/user-guide/libraries/sessions.html
If you still consider using multiple queries, you could write a function in one of your models which will return an array with the data of the user.
EDIT: You can also join the results in one Query, this way you only need one query.
Here is a good start:
http://ellislab.com/codeigniter/user-guide/database/examples.html

Adding entries into database instantly or after filling out form

I'm working on a PHP/MySQL application that allows for organization members to be maintained within the database. Currently, upon clicking on a "Add Member" span, I insert a blank entry into the database and return the created ID to PHP. Upon receipt of a valid ID, the application user is redirected via jQuery to an edit page that refers to the newly-created member.
As far as I can tell, this has the following advantages/disadvantages:
Advantages
Can instantly associate purchases/payments with a member upon submitting a jQueryUI dialog, since I already have the ID of that member.
Unifies what would have been separate add/edit screens, so easier maintainability on my side.
Disadvantages
There is a high possibility that I will have stale entries. That is, someone could click on "Add Member" multiple times and not save the new page, therefore causing entries to remain blank.
Not able to enforce as many constraints in the table, since I need to be able to accept NULL for all of the columns.
Am I thinking of all of the scenarios/advantages/disadvantages? Should I make a separate page for adding members, or is it better to accept the stale entries, and possibly add a few checks when I fetch all members to make sure that I'm not displaying a stale entry?
My database function for adding members currently:
public static function addMember()
{
$q = 'INSERT INTO ' . MemberTable::TABLE_NAME
. ' (' . MemberTable::ID
. ') VALUES (null)';
try
{
$db = new DBConnection();
$toRet = $db->execute($q);
}
catch(Exception $e)
{
error_log($e->getMessage());
$toRet = -1;
}
if($toRet > 0)
{
DBSystemEvent::logMessage("Added new member with ID $toRet");
}
unset($db);
return $toRet;
}
EDIT 1: After rereading the question, I need to clarify that members and users referred to in the first paragraph are different. Users refer to the person logged into the application. Members are not able to log into the application. This is similar to a hospital application (patients may not log in or edit their own information; only application users such as nurses or doctors may log in and edit information).
EDIT 2: While none of the given answers completely fit my problem (since I may have to insert into the database without knowing an ID), I decided to accept an answer based on how my question was worded (since making it any more specific may cross into too-localized territory).
It's a common problem - you need to know the ID before INSERT, but it's known only after. So there is only one adequate solution: use GUID (http://en.wikipedia.org/wiki/Globally_unique_identifier) instead of autoincrement ID. Generate guid from PHP code, for example com_generate_guid(), and do not preINSERT empty rows at all. And make relations between tables with GUID fields.
It's little bit unclear to me what exactly is the workflow of your site.
If user comes to you page then I assume that he must login from where you get his ID. If he is new user then he is redirected to userdata.php?id=0 where he enters his data. After submitting you should check if $id=0 and if the user with the same username/id/.. exists (SELECT... WHERE ID=xxx) and warn user to change his username. If no match is found then you can do INSERT and obtain the new ID.
If in future user wants to change his data then after login you can direct him to userdata.php?id=123 (where 123 is his ID). Then you can check if $id>0 and do UPDATE.
If you can, switch to postgresql. This will allow you to use a sequence to provide you with a unique ID without entering empty entities into you database.
Funny enough one of my clients is using the same approach you haven chosen and so far this lead to a lot of maintenance and work load overhead to weed out the empty entries from the db.
If you cannot use a database that offers sequences consider using an otherwise empty table which only atomically gives you unique ids. That way you can already start using the id to prepare relations on the client side and then enter them in bulk into the db when the member is finally created.

PHP: active Users

I just faced a problem. I am currently working on a project for school and I want to have all active users in the Sidebar (similar to a chat, but it's not).
First I thought of this (Pseudocode):
<?php
...
class user {
//Some instance vars.
public function __construct(){
//Write username in a textfile/database
}
public function logout {
//Delete username from textfile/database
}
}
...
?>
The problems are:
1) The user-object is stored in the $_SESSION[] Array. So I can't use the magic method __destruct(). That's why I made the logout() Method. (Problem solved ^^)
2) If we assume that the user is logged in on 2 devices (eg. Laptop, Smartphone) with the same ID and he quits the session on one device, the other device will also be removed.
3) The user probably doesn't want to press the logout but and just closes the browser window. How do I know, that he logged out / quit the session.
I know, that PHP is not the best programming language for this kind of task, but I really want to do this project in PHP. I am really sorry, if this question has already been asked, but I carefully searched through all related questions and all of them differ (more or less) from mine.
Thanks in advance :)
I think a much better approach (and the one that's usually employed) is to have a table that contains two columns. The user id and the last time that the user was active on the site.
You'd keep this table up to date at login and potentially each time a user loads a page or performs some significant action on the site.
To show who's online you then query this table for any users that have been active in the last N seconds/minutes.
You may optionally wish to add a "cleanup" job that removes users from the table where their last activity was more than (something >N) seconds/minutes ago to keep that table from becoming too large.

How to hide pages from certain users in angular and php

I'm creating a website in which users can create some profiles.
All profiles must be open for viewing only to users that the creator has chosen. The others won't be seeing them.
Using angular, you can easily create pages using routes, so of each new page you will have something like:
www.example.com/profiles/profile/1
www.example.com/profiles/profile/2
www.example.com/profiles/profile/3
etc.
But, say, you own profile 1,2,3 you can easily view profile/4, profile/5 etc...
How can you implement a system that prohibits viewing, or allows to see less data than the access-granded users?
Thank you.
As told, the answer should be server side. authentications should always be server side..
In your case, you need to query the database only once like you have done so far, actually the correct term will be just sending a http request to your api (as the http requests is doing the db queries). that http request should start by checking what kind of permissions you got and return the appropriate data (limited list of users, a specific user or an error that you don't have access to that specific content).
I hope it makes sense to you.
If using a database you can add a column AccessRights
0 = Basic
1 = Profile 1
2 = profile 1/2
etc
Different integers of AccessRights will let you access different things.
and to stop people with access rights 1 from accessing accessrights 3 material
if ($Accessrights < 3)
{
die("You Cannot View This");
}
it will be up to you to assign a variable for $Accessrights or something.
Hopefully this is something your looking for
So do I have to query the database on each page a user visits? Wouldn't that be too resourceful?
The access system that I want to create is something in the same vein as facebook.
You can see your pages and your friends pages, but you cannot see the private pages.
You can edit your profile, but not othe peoples profile.
Is this the right way to go?
You could check if the user is viewing his own record or if he is allowed to view any record
$iUserType = USER_TYPE_ADMIN; // constant
$iUserId = 5; // this and user type can be stored in session after login
$iViewProfileId = 5; // this should come from the request parameters
if (($iViewProfileId != $iUserId) AND (USER_TYPE_ADMIN != $iUserType)) {
// error, user is not permitted to view the record
}

Categories