codeigniter database calls from view - php

Hey guys was hoping you could help me out.
basically i'm working on a website created using codeigniter by someone else. The site has two instances, one for development and one for live. The site is still under construction which means files are constantly being changed and moved from the development site (after being tested) to the live site.
Now the thing is, the person who initially created the site made some database calls from a few views. And to access the database from the view, he manually connected to the database from the view, i.e using
$db=mysql_connect(...);
mysql_select_db(...);
This means that each time a view is changed, before copying the files from the dev site to the live site, we need to change the variables inside these views.
moving all queries to models, and then calling them through controllers would take too long, so was wondering if there was a way through which i could access the database variables in the database.php file and pass them as the variable for mysql_connect.
i tried $this->db->database but get the error "Undefined property: CI_Loader::$db"
thanks in advance

There is no way to access database object from view. And you should also not do
$db=mysql_connect(...);
mysql_select_db(...);
in view. Try to remove those calls from view. And call it from model.
That is what MVC in codeigniter used for. Othervise what is use of using codeigniter framework.
See also:
access model from view in codeigniter?
CodeIgniter - Calling a function from inside a view

Define constants in constant.php assign them database username , password , host name etc and use them anywhere you want

First of all don't be eager about moving database calls to views, than take a look at this answer: https://stackoverflow.com/a/5835321/1444604

If this site is under construction yet, it shall be much better fix all this programing issues now than later.
Remembering that mysql_* codes are deprecated and won´t go much longer be accepted by hosts.
A hint that you could use what sometimes we forget, are those options of replacing texts presents in som many text editors and IDE´s, normally with a shortcut ctrl + H, you can rewrite a lot of code in many files, but be careful, or this can get all worse.
Well... said that, what you´ve tried to do in the view $this->db->database() maybe can work if you use this code before load database. I think it should
work just like as when creating libraries.
$CI =& get_instance();
Give a look on, but even if it works, avoid it as much as you can:
https://www.codeigniter.com/user_guide/general/creating_libraries.html
Good Luck!

Related

What is the best way to store AND update global variables programatically for your website in laravel 8?

I need to store some global variables for my laravel website, but I need to update them programmatically. Here is my situation:
the admin should be able to enable popups, and configure which post it has to link, which will show when a visitor comes to the website.
Other answers and why they did not satisfy me.
Making a laravel config file.
A database table.
Static variable somewhere in a controller or model.
A Laravel config file seemed to be the best option at first, but it didn't fit with the need to update them at running time. I've readt answers that suggested to call an artisan cache clear in the controller in order to update the values. but this seems just off to me. I don't think its a good idea to mess with the cache like that.
A database is still an option, however, it has some downsides as well. Making just an SQL table for 2 config variables seems like a waste of tables, it also means i need to make 2 query's on the admin dashboard, and also 1 on the homepage (to get the popup config), which i rather keep database-free.
A static variable in a model or controller. I saw this suggestion as well altough noted: it is probably a very bad design choice. Nevertheless i tried it in a desperate attempt and it didnt work. It did not stay updated on page reload.
I'm a laravel noob in case you didn't notice. Is there anything I am doing or understanding wrong? Or is there a solution I am not aware of?
There is no need for me to save the variable when the website is offline. It would be nice if it did but its only a minor inconvience for the admin to set it on restart.
For your situation, spatie write a nice package.
Just install as in documentation and use.
Use a db table to store the configuration, also having one extra table does not have any serious downside and it won't hurt the performance, also most popular applications/frameworks use it.
To reduce the db queries, create a wrapper class for your db config load, and in your wrapper cache the data for some amount of time, and when you want to change the config, remember to invalidate the cache.
If you want global access to it, bind it to laravel service provider, and use Facade or other container methods to fetch it. Also with this approach you keep the exposed config interface the same even if you change the implementation different in future.
About file solution: If you have one admin, you can go with file solution, but you never know how they will grow in numbers in future and it will be a hassle to go around what you did in file.
You can set config values dynamically at runtime with config() helper:
config([ 'app.popup1' => true ]);
Another solution is to write the config value into session at startup and only update the session:
session([ 'app.popup1' => true ]);

how to prevent access database and resources in laravel blade?

I want to create a shop builder that the user can create own theme and upload it to my host. and now I want to prevent users cant access database and model and resources in blade.
Because they can write malicious code through the blade on my server and cause system crashes.
I want to send only a list of variables for each blade's page that contains the values ​​they need on this page and users can only use these variables and can not access my server database or resources and my files server.
I had to prevent user cant access database in the blade
Anyone have an idea for this؟
thank you
I have a need similar to yours
after several experiments and attempts I have found a solution that might work,
but with limitations/restrictions
it would be appropriate "from my point of view" to think about introducing another way to render your content.
in the face of my research I have found 2 possible solutions
introduce liquid
PRO
no type of access to the code
AGAINST
everything that will be accessible must be processed in advance
introduce TWIG
PRO
you do not have default access to eloquent or anything else that has not been passed to it
you can pass an 'object' intended as a php class with all its methods and properties
AGAINST
just because you can pass 'objects' you may come across the unpleasant condition that an object brings with it something that the view should not have access to
conclusions
in conclusion, 'my' choice was liquid, since it guaranteed me more security, in addition to other companies such as shopify have decided to use it also for this peculiarity

Where should I store the Laravel Session data based on the MVC pattern?

I'm working with the Laravel integrated to the WordPress and struggling to understand where should I put the session data based on the MVC design pattern?
Back in the day, I used to put everything inside the view (header.php and footer.php) files and after some time, it became a mess, complete mess.
As written here:
As MVC I use CodeIgniter, so I don't know if this can be true for your specific environment, but I usually set session values from the controller. It is possible to do it even in view but the correct way is to keep code in controller (as keeping database stuff in models).
In the controller, you can use standard php $_SESSION array or, it it exists, your framework session class.
Yea, I understand it's a good practice to not mess around with the view and put session variables inside the controller. Here is the problem:
As I'm using the WordPress, the goal is to have a place where the session variables are always loaded, doesn't matter if I changed the theme or anything, they should stay in the Laravel backend.
Without any testing, I could think about a couple option:
Use Laravel Service Provider and insert session variables inside the boot function.
Use Laravel Middleware functionality, however, not sure how to implement this.
You can use the laravel https://laravel.com/docs/5.6/session Session helper.
Then you can just do Session::put('hello','world'); Session::save(); and retrieve it with Session::get('hello'); You can do this anywhere you'd like, as long as you remember to save the session after putting things in it, modifying things or removing things.
As long as Laravel is loaded and the domain has the laravel session cookie, you can access them.

CodeIgniter: Appropriate place to put reusable functions with database calls

I'm new to CodeIgniter but want to perform best practices from the start. I have a simple authorization call that needs to be able to be called from several controllers. Hence I'm thinking it should be placed in either a library or a helper function. The call would take the user's id and a required authorization "level", grab their information from the DB, make sure they have that level of access, and return true or false.
Let's say:
auth($user,5)
My first instinct is to make this a library, but it seems odd to place it directly in a library because there are DB calls, which I would think should go in a model. It appears that only the Session library contains calls directly to the DB (for when database session storing is turned on).
So, I could access the DB directly within the library, or try to link to an external Model. Looking it up on the web, I'm only finding people who have trouble with both routes. Before I dive too deeply into getting one of them to work, I'd appreciate any opinions out there on how to go about this.
Thanks,
Jeremy
It seems like that is a model function. At least put it there until later in development.
If you later find there is a need for multiple models which would require duplicating the function, then would be a good time to move it to a helper or library.

Beginner CodeIgniter concepts - Reusable view code, where to go? (Helper?)

I am a beginner with CodeIgniter still struggling to get a complete grasp on how to use the MVC ideology most cleanly.
I am writing a basic CMS system with the ability to vote on entries and follow people etc, consequently, I have found myself using the same or similar pieces of code across multiple views here and there consisting of various pieces of html and logic such as:
Voting panel
Follow/Unfollow panel
Login/Logout panel
Code to check if a user is logged in etc...
I am wondering where to put this code so it can be unified? I am thinking a helper is the way to go? If I declare the helper in the controller, it can be called from the corresponding view right?
Some of the elements are dynamic - such as a follow/unfollow button - It would need to check if you are already following the user or not and display the appropriate button, which would require a model to check. What I have now is that all the logic is in the controller and it returns an appropriate button, but it seems weird to be returning formed html code in a controller return as well. Should it be more like:
controller checks if you are following someone
the controller passes a boolean to the view
the view calls the helper with this value to draw the appropriate button
Also, as a secondary question, I have been doing a fair bit of looping through mysql arrays in foreach loops to process mysql results returned from the view. It seems like my views are getting somewhat complicated, but I can't think of another way to do it, although perhaps this should be done in another helper as well?
Apologies if this is a naive or repetitive question, there is indeed a lot of discussion surrounding this subject but it is not always easily relatable to another project.
Helpers are certainly one way to modularize anything that isn't DRY. Another is to use Partial Views. CodeIgniter looks like it supports partial views. Here's a good breakdown - not PHP specific but the discussion should be agnostic.
As far as handling user logins is concerned, you will probably want to use a static class and the singleton design pattern, which will allow you to check to see if a particular user is logged in or not anywhere in your application. There is a good tutorial here
http://www.phpandstuff.com/articles/codeigniter-doctrine-scratch-day-4-user-login
Loading the helper, I don't believe loading it in your controller will automatically load it in your view. I think you have to re load the helper in your view file, or you have to autoload the helper. (cant remember off top of head but Im pretty sure).
Regarding looping through the mysql results, you should be using a model for this, always. Any functions which are grabbing or sorting information from your applicaiton, should be done within the model. Then, in your view file you loop through the results and format the data how you choose to.
When developing http://newspapair.com which has the vote functionality you mentioned I used helpers and custom classes to spread the functionality across multiple views.
Helper - has functions without a class. So a standalone function or group of functions can be placed in a file and saved as a helper.
For instance I used a helper with generic form processing functions for NewsPapair, instead of a static class. But this is not the "best practices" thing to do. I did it this way because I already had the functions from a previous project.
As far a looping through MySQL results, try to write a query that allows the DB Server to do the heavy lifting. This will make your code more efficient. Perhaps ask a question about a specific query with example code. Plus do all of the data gathering in your Model.

Categories