Best way to setup a variable for Global use in CodeIgniter? - php

I'm using CodeIgniter and I have user data that needs to be stored in some way then updated. Basic things like name, id, points, comment count etc
At the moment when the user logs in I simply get their data and store it in a session. Now obviously the name and id would never change, but the Points and Comment count etc will change from page to page depending on the user actions.
As this data will be constantly changing, what would be the best way to store it , update it and make it available throughout my app? I'm not sure if updating the session every time the user performs an action is the best way though?
I thought about maybe using a CodeIgniter hook to run a function that sets up a variable ready for use?
Whats the best way? Any ideas?
Thanks, Sean Jenkins

Why can't you store the data in a database? If your worried about performance you could use something like Memcache or APC to cache it but it seems like comment count and points are data that need to persist between sessions.
You would still need to write the data to the database as well as the cache but then you could read the data directly from the cache instead of querying for it.

Related

Php Globals v. Database calls for lots of data

For large arrays, is it better to save the data to global variables or query the database each time I need them? In my situation keeping them local scope and passing them to functions isn't an option.
I'm using wordpress and in most pages I get every user and all metadata attached to them. Often times I use these variables in multiple places on the same page. Unfortunately wordpress won't let me pass variables between templates so I'm stuck either using global variables or calling the database each time. Eventually, this will be hundreds of users with a lot of metadata attached to each. Should I call the database each time to keep the variables local, or should save them to global variables to save on database queries? What are the considerations? Should I worry about performance, overhead, and/or other issues?
Thanks so much!
The only real solution to your problem is using some kind of cache system (Memcache and Redis are your best options). Fortunately, there are plenty of Wordpress plugins that make the integration an easy thing. For instance:
Redis: https://wordpress.org/plugins/redis-object-cache/
Memcache: https://wordpress.org/plugins/memcached/
EDIT
If you only want to cache a few databases calls, you can forget about Wordpress plugins and start coding a bit. Let's say you only want to cache the call for retrieving the list of users from database, and let's assume you are using Memcache to accomplish this task (Memcache stores key-value pairs and allows super fast access to a value given a key).
Query Memcache asking for the key "users".
Memcache still doesn't have such key, so you'll have a cache fail and after it, you'll query your database to retrieve the user list. Now serialize the database response (serialize and json_encode are two different ways to do this) and store the key "users" along this serialized value in your memcache.
Next time you query your memcache asking for "users", you'll get a hit. In this moment you just have to unserialize the value and work with your user list.
And that's all. Now you just have to decide what you want to cache and apply this procedure to those elements.
You shouldn't have to perform the calls but once per page, you might have to execute the call once for every page. So I would suggest you creating some sort of class to interact with your database that you can call on to get the data that you need. I would also recommend using stored procedures and functions on your database instead of straight queries since this will help both with security and separation of application logic and data functionality.

Database storage vs Cookies - To store form data

Good day to all,
I have a form with around 90 to 100 fields, divided into sub forms, which are loaded using ajax each time a form has to be displayed. but i would like to retain the data on the form fields every time a subform is loaded(lets say on an accidental page refresh or even if the user is switching between sub forms). What is the best way that this can be done.
I was thinking that i can store it in cookies or lets say in the database. But, storing it in the database would mean that i would have to query for the fields data every time a sub form is loaded. And again, if it was cookies, it has to read the data stored in the cookie files. I need some help with deciding what is the most efficient way, more in terms of speed.
What is the best way among these, or is there any other possibility to retain the fields data in the sub forms, every time they are loaded (which are loaded via AJAX each time.)
I am working with PHP and Codeigniter framework.
Thanks!!
A form like that needs to be durably stored. I would consider session state to smooth out the sub form loads, with writes to the database whenever the user updates something of consequence. Personally, I would start with a database-only solution, and then add session state if performance is an issue.
Cookies aren't meant to store large amounts of data. Even if it were possible, they bloat the request considerably (imagine 100 form fields all being transmitted with every request).
Local storage in the browser is also an option, though I would consider other options first.
I would first simplify it by using serialize:
$data = serialize(array_merge($_POST,$olddata));
Then that may be enough for you, but it's now super easy to store it anywhere since it is just a string. To reform it into its original state:
$data = unserialize($data);
.. wherever you end up pulling it from - database,session,etc..
Prose of database
It can also access from other computer too
You can store far far more data then cookie
Cones
If you retrive data by ajax it coukd cose more load on server
Cookie
Faster than database no query , fetch and all process .
Cones
Limited amount of space
However you can use local storage
So answer is database storage

What is the best way to store a column sort order on website?

Here is what my table looks like: http://jsfiddle.net/Draven/kGtx7/14/
Each header cell is clickable to be able to sort by that field and by ASC / DESC.
I want to be able to store that sorting option somewhere, so it get's remembered, but am not sure the best way to do that.
Here are the options I was thinking...
Making sort_field and sort_order fields in the users table
Making a new table that has their userid along with sort_field, and sort_order fields
Or Cookies, but I assume this is the worst option
I don't think we are clear on what you want, but I think you are wanting something like this:
Step 1: Run a query than will populate the sorting values into 2 session variables.
Step 2: Do something like this code.
$sortHeadClicked = $_SESSION['headClicked']
$sortReturnDirection = $_SESSION['returnDirection']
//TODO: validate data before query
if ($result = $mysqli->query("SELECT * FROM table ORDER BY $sortHeadClicked $sortReturnDirection))
{
//TODO: Get results
}
Step 3: Smile like your awesome
Alternatively, you could use some sort of sub select query.
NOTE: This is the simplistic logic so they won't be remember with this example. However, you can put the gets into session variables if you only want them to be remember temporarily
However, if you want these remembered permanently, you need two columns in your user's table where you would either puts them into sessions or use a subselect query
This is left up to interpretation, but each case would have its own uses.
1) Adding two fields to your users table will make the calls to retrieve these values easier but it is a much uglier approach to the problem than..
..2) Relational databases are built to be used as such. I'm not sure in terms of performance, but I do know that using the power of relational databases can make your db easier to navigate and understand/manipulate. While you may need some more complex calls (ie joins and whatnot), I believe the tradeoff is worth it.
and 3) Cookies are a very meh solution. They could be used in temporary cases, but if you are trying to save info for later, cookies can easily be deleted or not even enabled, at which point your site can suffer drastically.
Actually, using a cookie to store the user session id and then keeping session data in a database, flat file, or memcached is pretty common way to solve this. It would help to set up a reusable mechanism for this, like registry of sorts, that you can retrieve per user values at will. This only works if you have a user login of course. Otherwise there is no point in storing that data, as the users identity will be lost once they end the session (close the browser window). Most web apps will use cookies to identify you. If you delete that cookie, it forgets you and you are logged out.
Your first solution will suffer if you ever want to add another per user "preference" as you'd need to modify the underlying table.
Have a look at Zend Session for ideas if you are using PHP. If not the concepts still apply.
To save the sorting order to their profile, make the table inside a form and have the sortable field names be inputs. When they click one of the field names (sort by Location, for example), have the form's action run a PHP snip that updates a field in their profile on the database.
Alternately, if able to use ajax, you could simply add the database updating to an ajax call and skip the form.
I'm afraid that depends on your needs. How I see this problem:
good if you must share this settings between browsers, PCs, in
case if user delete cookies in browser. But it is not flexible - if
you will need to add another table, you will also add two additional
fields
the same as 1 in term of how it is shared between computers, browsers etc, but it is more flexible. You may add a column with table name easily.
If this setting is not so important and you may allow to loose setting in some cases. This solution is simplest, but it may not work for you

Storing users 'following' during a PHP session

I have a simple followers/following system set up within my app.
What would be the best way to store a complete array of 'users following' during a session so that I don't have to query the database multiple times throughout.
To clarify: When a user logs in once they have been authorized I query the database, get a full list of users that the logged in user is following and ultimately store it as a JavaScript variable. This way throughout the site, as the user navigates around I can constantly check the following status against any other user they may come across.
This query is only performed once when the user loads the full page, while navigating around it is not repeated.
This works well for javascript generated content i.e user hovercards etc...
However I would like to store this array (of only userid's) in PHP itself so that I can prevent further queries to the following table while generating content server side that requires a 'follower/following' check to be performed.
What would be the best way to do this?
Please bare in mind that the results are cached in memcached but if I can avoid any lookups at all and have a consistent array to check against that would be great.
Thanks in advance
So let me get this right, you want to store this list so it isn't queried on each page?
First I would recommend you only perform this query on pages that need this data and second I would say that on these pages you don't try this.
Imagine a user stops following or starts following. Some complex cache calculator or event bubbler programmed into your own PHP app to purge the foreign session of data (which is bad, the user has access to data that is not their own, a session infact) could be tiedious with security and performance.
The better thing to do is to perform the query again for each new page. This would be much easier, probably more performant and wouldn't be micro-optimising.
Edit
If you are picking out 10k rows on one page then you might be doing something wrong. You might be looking at it from the wrong perspective.
Store it in the session variable.
http://php.about.com/od/advancedphp/ss/php_sessions.htm
https://www.google.se/search?q=learning+sessions+php
UPDATE
Store the current user in a session and add it to the queries you are already doing to fetch the popup information and add that it tests if the popups person follows the current user.
The two ways that come to mind would be to just write joins with well placed indexes each time, which you've said you don't want to do, and just a simple array in the session, which would probably look something like this:
if (!isset($_SESSION['following']) {
$following = $user->getFollowingIds(); //some query in here to get an array of ids
$_SESSION['following'] = $following;
$_SESSION['following_str'] = implode(',', $following);
}
Then whenever you want to pull all of the statuses for the people that $user is following you can write a query, something like this:
$query('SELECT status.* FROM status WHERE user_id IN (' . $_SESSION['following_str'] . ')'); //not sanitized or safe but you get the idea

PHP One time database query on application startup

I have a ajax based PHP app (without any frameworks etc.).
I need to retrieve some records from the database (html select element items) ONCE, and once only, during application startup, store it in a PHP array, and have this array available for future use to prevent future database calls, for ALL future users.
I could do this easily in Spring with initializing beans. And this bean would have the application scope (context) so that it could be used for ALL future user threads needing the data. That means the database retrieval would be once, only during app boot, and then some bean would hold the dropdown data permanently.
I can't understand how to replicate the usecase in PHP.
There's no "application" bootstrapping as such, not until the first user actually does something to invoke my php files.
Moreover, there is no application context - records retrieved for the first user will not be available to another user.
How do I solve this problem? (Note: I don't want to use any library like memcache or whatever.)
If you truly need to get the data only the first time the app is loaded by any user, than you could write something that gets the data from your database, and then rewrites the html page that you're wanting those values in. That way when the next user comes along, they are viewing a static page that has been written by a program.
I'm not so sure that 1 call to the database everytime a user hits your app is going to kill you though. Maybe you've got a good reason, but avoiding the database all but 1 time seems rediculous IMO.
If you need to hit the database one time per visitor, you could use $_SESSION. At the beginning of your script(s) you would start up a session and check to see if there are values in it from the database. If not, it's the user's first visit and you need to query the database. Store the database values in the $_SESSION superglobal and carry on. If the data is in the session, use it and don't query the database.
Would that cover you?

Categories