Codeigniter--How do store info? (noob) - codeigniter

I'm building my first real CI app. I have to build a survey system--If the specifics are important, I'll elaborate.
What is the best way to post the info to the db from the user? In a single row, comma separated? I'm a noob here, so detail would be appreciated! :)
I should add: the user needs to have the ability to try multiple times for the test and have each test's score charted. Payment is required to take each test.
Here's where I'm at. This code works, but I'm sure there's a more elegant way to do things.
$this->db->select('credits')->from('be_user_profiles')->where('user_id', $this->session->userdata('id'));
$query = $this->db->get();
foreach ($query->result() as $row)
{
echo $row->credits;
}
What about this?

That's more like a code organization / code structure question than a problem.
You can fetch your input data "by hand" or use Active Record CI library to do that (https://www.codeigniter.com/userguide2/database/active_record.html#insert)
If CI has ORM implemented, the job should be even easier than this.
Just create a controller and check the input data on it (or inside the model) and create a model to apply the necessary cleanups, data verification and proper data assign to one or mode tables and you're set.
edit : more elegant than the example you've showed would be with ORM, but I'm not sure CI has that implemented yet.

It depends on how the data is structured, but your best bet would be to have a survey table, and store the answer to each question in a different column.
From an MVC point of view, you would have a form in a view, have the controller pass the data from that form the model when it is submitted, then have the model clean the data and insert it into the database.

Related

Laravel - 2 queries over nothing?

Hello guys,
in the official doc of Eloquent for Laravel, this is the way to make an update to a table :
$flight = App\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();
I must say, I don't really understand that. For me, it means that for a very basic update, there will be 2 queries to the database - a select and THEN an update ?
Anyone could explain me why this would be a good solution ?
Thanks !
Any abstraction is used for complex applications. The code is too simple that you can not feel it advantage. The Object Relation Mapping (ORM) is used to hide details of operating databases, or running SQL queries.
Just like the MVC model, different layers are in charge of different fields.
View: render HTML
Controller: Logical control, like if .. else ..
Model: data access, like data modification and persistence.
The controller layer won't take care of how model layer works, you just find a object like $flight, and change its property, and save(). That is natural and neat. Your controller layer are all about Object modifying, instead of data modifying.
By separating data and object, you can easily, or at lease possibly, change the implementation of data persistence.
If some objects are frequently changed, you can save it on Redis or Memcached or other NoSQL storage. The controller layer's code needs no change.
If some objects are very large and not modify quite often, you can consider using some distributed storage, or using lazy loading techniques. Your controller code also unchanged. You just change the model layer's implementation, the upper codes will not aware of the change.
Decoupling or layering codes, makes it easy to change any layer's implementation. If you think wring two lines of SQL queries is quicker than ORM, maybe you need to experience larger projects with highly demand changing and performance optimization.
It is always good that separating the implementation and the usage.
Edit:
You can use where and update to update by id. See http://laravel.com/docs/5.1/eloquent#basic-updates
App\Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]);
There is some benefit of using this approach if you want to ensure that you're modifying only one valid record.
On the other hand there is another way in the documentation:
App\Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]);
It's your preference whether you need to ensure the single record modification or not.

Correct MVC design for Symfony/Propel?

If making things work is only requirement, we can put all controlling login and DB handling logic even in the views & it will work. However this is not a right approach for reusable design.
Before I ask my real design question, below is my current understanding about separation of responsibilities in terms of model.
All Database related code, even db related logic, should go in models.
For a table, say 'my_tab', propel generate 4 classes, out of which only 2 classes 'MyTab.php' and 'MyTabPeer.php' should be edited.
MyTabPeer.php must only have data fetching.
Any logic, if required to fetch data, should go in 'MyTab.php'
This is simple and I hope it is correct, if not, please correct me.
Now, I have a special condition. I've 4 tables, say a, b, c, d. For that, propel generated 8 editable classes (excluding base*.php)
A.php APeer.php B.php BPeer.php
C.php CPeer.php D.php DPeer.php
One page of my application, shows Mailbox (say). Mailbox is not a table in database but it gets its data from complex join query between above 4 tables along with lot of calculation/conditions.
I generated that query, fetch data from it and displayed it. Mailbox is running as expected. However I did it in my controller (action class), which I know is not a right place for that.
My question is, where should I put that code? Possible options:
Controller, I think, is not a right place for DB logic/fetch.
I've 8 model classed however data do not belong to any one of them but as combination of them all.
A separate helper/lib, but I know I'll never reuse that code as its unique page of the site.
Anywhere else?
Please suggest if I'm wrong but I guess I should put it in models as it is fetching data. Since A is primary table, I probably should put code in A.php and APeer.php. If that is correct place, next question is, What should go in A.php & what should go in APeer.php? I've following operations to do:
Some logic to decide what columns, should I select.
As like mailbox, I can show received/sent message. Controller will tell what to show but there are some db logic to set conditions.
Then really fetch data from complex Join query.
Returned data will have all rows but I might need to merge few rows conditionally.
As per my understanding, Point 3 should go in APeer.php and rest in A.php. Is my understanding correct?
You should create separate model class i.e. Mailbox.
Method of this model should do the complex select and return data to your action in controller. This solution will not break MVC approach.

CodeIgniter MVC Model Logic

I have programmed in Rails, Django, Zend, and CakePHP. Also, Wordpress and Drupal.
Now, I am "catching up to speed" in as fairly large application in CodeIgniter.
Typically, my experience with MVC frameworks, has led me to believe that Models represent business logic in reference to actual database tables. In the CodeIgniter docs and in the code base I'm dissecting I see models created that represent something as vague as a page. A lot of the business logic is written directly into those models and they incorporate other actual data models. I'm not sure this is ideal and following MVC.
Should models be created beyond data models?
Also, lets say I have a data model representing a user (user table in DB). In that user table there is a column called gender of the type enum('male', 'female'). Now I want to populate a dropdown with the gender options from the enum column.
Where is it most appropriate to put this logic?
The user model is an object used to represent a single user or row in the db... right? So it doesn't seem fitting to include a function in the user model/class called "get_gender_options", because, while the function is related to the user table, it is NOT relevant to a single user object. In Zend this kind of logic could be built into the form object itself.
There is not "right" answer, just one we can consider the most appropriate...
I would probably just put the "get_gender_options" in the model, rather than sticking it in the view for the form. To keep it DRY but not put it in the model, I would create a helper to hold this.

MVC (codeigniter) design question

users want to see some reports from stored data in the db
for example:
all sales in a time interval (user submits a just a time interval),
all the sales in the selected city in a time interval (same with above but this time extra city select dropdown),
top selling 20 shops (another report , no form submission and different db tables involved ),
etc
My problem is
how can i accomplish these task without writing a separate model, controller and view for each report
or
each report has a method in a single controller and model and two views (one for form submission 1 for results).
i must tell my background is procedural programming and i am confused. everything seems like writing basic "switch case" in a really complicated way.
thank you.
This depends on how you structure your db. Although having lots of models might seem like overkill I would suggest that if you approach it in the right way you will find it makes your life easier. For example you could have a model that deals with sales. Within that model there could be a function to retrieve all sales by date or time. This function could have an optional parameter to allow you to filter by city. You might then have another function in the same model to retrieve the top 20.
From the controller you would have one function. This would be one big if statement based on whether or not the user had submitted the form. If not then display the form view (it is best to have separate views for specific things or at least fragments of views). If data has been submitted then simply test the data to find out which report is required, query the relevant method in your model and send the results to another results view.
This way, one controller, one model, 2 views ( or more if you're using a template kind of thing).
I deliberately haven't written the code for you, but I hope this points you in the right direction. Please comment if ive misunderstood the question or you need clarification.

CodeIgniter Many-to-Many Relationship Management

Can anyone point out a good many-to-many database tutorial for CodeIgniter.
Just trying to work out the process of creating, and then updating a many-to-many relationship. My example uses a multi-select of values, wondering how you take care of monitoring changes on update etc.
I'd like to share what I do in my application. This is basically same with my answer in this question.
After user submit, and before entering to database, I will fetch the existing data in the database into an array. Example: $collection = array('111', '112', '113', '114'); (This is just for example. In real, it should fetch from database then put the value to array)
I will check the new user input in two step. First step is to see if it already in the database or not. If it not, then insert. Otherwise ignore:
foreach ( $inputs as $input )
{
if ( ! in_array($input, $collection) )
{
//do insert here
}
}
Then in second loop, I do it in reverse, to delete the data that not selected by user.
foreach ( $collection as $data )
{
if ( ! in_array($data, $inputs) )
{
//do delete here
}
}
In your case, you might or might not need the second loop. I needed this since I make the input as checkboxes, that the user can choose to activate / deactivate, thus I translate it as insert and delete.
Since you will implement it using multi-select, then basically it's same with my checkboxes.
If you have structure or code example, feel free to share it, and I will help you fine tune it (of course with my style, that might or might not optimized yet).
This website has some tutorials for many to many. It uses doctrine though.
http://www.phpandstuff.com/articles/category/tutorials
The codeigniter from scratch series will cover almost anything you want to know about the framework
http://net.tutsplus.com/videos/screencasts/codeigniter-from-scratch-day-1/
hope that helps. there are 7 to date btw

Resources