best way to preventing form resubmission of codeigniter - php

Always confused about form resubmission . I know Header and session are the right way. But I don't know how can I proper use in codeigniter. Suppose
For single insert and update query
$this->db->query(' insert/up query');
$this->session->set_flashdata('success_message','successfully inserted');
redirect('my_contoller/home/index');
For pass $data array
$data['pass_data']="some array elements";
$this->session->set_flashdata('pass_data_from_flash_data',$data['pass_data']);
redirect('my_contoller/home/index',$data);
If above technique are right how can I pass query's data for retrieving. Suppose I have a query which return many data. Such as
$query = $this->db->query(" a query which return large data");
$data['return_large_result']=$query->result_array();
I just confused to using set_flashdata function. Is the right way?

The above method mentioned you are using is a valid web development design pattern. Codeigniter is a bit messy for this method but essentially yes it is the right way within Codeigniter.
Other frameworks such as Laravel support this feature better, allowing you to access old input via Input::old() amongst other methods.

Related

How do i fetch data inside a controller using laravel

I just started learning laravel.
I don't know how can I fetch data inside a controller,
I want to use that data inside a controller to make more rules.
//Get Data From Database
$db = DonorDetail::where('donation_id', $paytmResponse['ORDERID'])->get();
$name = $db['donor_name'];
$email_id = $db['email_id'];
DonorDetail is my model to connect to my database.
I tried this code, but getting undefined error.
I'm trying to select only 1 row using the unique donation_id and use data of other columns of data inside my controller.
get returns a collection. You should use first to get the first result from your query:
DonorDetail::where('donation_id', $paytmResponse['ORDERID'])->first();
If no results were found, null will be returned, so you should also pay attention to that.
You only provided us with a small portion of your code, but it seems like you're doing a lot of things in a non-Laravel way. It's only natural because, as you mentioned, you're just starting with Laravel. My recommendation to you is to check out Laracast's free "Laravel From Scratch" course:
https://laracasts.com/series/laravel-6-from-scratch
It's by far the best resource for developers taking their first steps in Laravel (and it also has good resources for experienced developers).
Good luck!
you can use dd() to see the data.
dd($db);
However, If you want to fetch only first matching data, use following
$db = DonorDetail::where('donation_id', $paytmResponse['ORDERID'])->first();
$name = $db->donor_name;
$email_id = $db->email_id;

yii ActiveRecord always querying database

Using Yii 1 and ActiveRecord -
I'm pretty new in both.
$types = CasinoSgTypes::model();
$types->findAll();
$types->findByPk(3);
I thought Yii AR will try to search in recently received data first instead of that I've got 2 calls to the database. Probably I'm using it in a wrong way?
sure i can walk through the array of results received by the first query (findAll) manually, but I'd like to do this by means of AR.
in other words is there a way to force AR search inside already received data and only then ask the database or smth like this. how to use AR+Yii models in a right way to avoid unnecessary queries ?
When you call $types->findAll(); the data isn't saved in the AR class and as such you cannot search using it. An easier alternative to searching in the data is to use query caching:
$types->cache(3600)->findByPk(3);

How can I execute an INSERT query on Twig (symfony 3)?

the problem than I want to resolve is than I want to see a list of users, and then I want to have a checkbox next to each user to select if the user is present or if it is ausent. On symfony (basic HTML actually) I can create an array than give me the id of those than I selected previously on the form, but, how can I send that information to the database? since I have this data on the view (which is a twig file on symfony).
So far I have only found this example of how to create a query from twig https://www.snip2code.com/Snippet/591299/hackishly-using-SQL-in-Twig-templates-in , but it give me an error since it doesnt recognize the "db", so I cant use it.
So, is there any way to to send that array to the database? Twig seems to limit a lot my options. Thanks
Edit: Correct approach (because someone else will have this noob doubt in the future, as I did) is in the method of the form (easier to make it work by just using html instead of what twig offer) call the method from the controller than you want to call, and there you can get the data with a $_GET or $_POST and then interact with the database with doctrine.
Twig is not limiting you. You are limiting yourself by using Twig in the worst possible way :) The main purpose of Twig is rendering your templates, not processing your raw queries. You're just ruining your performance, because the code which you write in Twig is read by a Twig interpreter first - that's unnecessary overhead.
You should put your database logic in services (use Doctrine for that - no need to write raw SQL for such simple queries). Use those services in controllers. And finally, pass the data from controller to template and render it using Twig.
If you want to have some dynamic actions after the page is loaded - write some simple JavaScript and make use of AJAX (background) requests to your controllers to send or get some additional data from your server. Or use Web Sockets if you prefer your data to be pushed to your page in real time.

Codeigniter, best practice for safe search

I am using codeigniter, and at the moment I am making full body search, and I am wondering what is the best practice to do this. For now I have this:
$keyword = $this->db->escape_like_str(trim($_POST['keyword']));
After that, search is performed. Is this safe or I need to do something more (XSS Filtering is on)?
Because you are accessing the _POST variable directly, you're bypassing all CI's XSS/Escaping and security features. You should be getting that as:
$this->input->post('keyword');
This is automatically escaped by CI, and you can perform other validations before just throwing it at the DB. Also if you use active record, then all values are automatically escaped as required too.

Separating code from DB functionality

I'm developing an object-oriented PHP website right now and am trying to determine the best way to abstract database functionality from the rest of the system. Right now, I've got a DB class that manages all the connections and queries that the system uses (it's pretty much an interface to MDB2). However, when using this system, I've realized that I've got a lot of SQL query strings showing up everywhere in my code. For instance, in my User class, I've got something like this:
function checkLogin($email,$password,$remember=false){
$password = $this->__encrypt($password);
$query = "SELECT uid FROM Users WHERE email=? AND pw=?";
$result = $this->db->q($query,array($email,$password));
if(sizeof($result) == 1){
$row = $result->fetchRow(MDB2_FETCHMODE_ASSOC);
$uid = $row['uid'];
}else{
return false;
}
/* Rest of the login script */
}
What I would like to do is find out the best technique for reducing the amount of inline SQL. I understand that one way to do this would be to write functions within User for each of the queries that User makes use of (something like the following), but that could lead to quite a few functions.
function checkLogin($email,$password,$remember=false){
$password = $this->__encrypt($password);
$uid = $this->do_verify_login_query($email,$password);
/* Rest of the login script */
}
function do_verify_login_query($email,$encpw){
$query = "SELECT uid FROM Users WHERE email=? AND pw=?";
$result = $this->$db->q($query,array($email,$encpw));
if(sizeof($result) == 1){
$row = $result->fetchRow(MDB2_FETCHMODE_ASSOC);
return $row['uid'];
}else{
return false;
}
}
So...my question. What is the best technique for managing the large amount of queries that a typical database application would use? Would the way I described be the proper way of handling this situation? Or what about registering a list of queries within the DB class and associating with each a unique ID (such as USER_CHECKLOGIN) that is passed into the DB's query function? This method could also help with security, as it would limit the queries that could be run to only those that are registered in this list, but it's one more thing to remember when writing all the class functions. Thoughts?
Having the SQL pulled out into separate functions is a decent start. Some other things you can do:
Create separate classes for database access code. This will help make sure you don't have SQL functions scattered around in all of your PHP files.
Load the SQL from external files. This completely separates your SQL code and your PHP code, making both more maintainable.
Use stored procedures when you can. This removes the SQL from your PHP code altogether, and helps improve your database security by reducing the risk that external SQL will get executed.
You might want to look into implementing the ActiveRecord Pattern. Using a design pattern such as this provides some consistency in how you work with data from your tables. There can be some downsides to these sorts of approaches, mainly performance for certain types of queries but it can be worked around.
Another option can be the use of an ORM, for PHP the most powerful are:
Propel
Doctrine
Both allow you to access your database using a set of objects, providing a simple API for storing and querying data, both have their own query language, that is converted internally to the targeted DBMS native SQL, this will ease migrating applications from one RDBMS to another with simple configuration changes. I also like the fact that you can encapsulate datamodel logic to add validation for example, only by extending your model classes.
Since you say you're doing this as OO PHP, then why do you have SQL scattered through all the methods in the first place? More common models would be:
Use an ORM and let that handle the database.
Give your classes one or more 'load' methods which use a single query to pull all of an object's data into memory and a 'save' method which uses a single query to update everything in the database. All the other methods only need to do in-memory manipulation and the database interactions are confined to the load/save methods.
The first option will generally be more robust, but the second may run faster and will probably feel more familiar compared to the way you're used to doing things, if either of those are concerns.
For your login example, the way I would do it, then, would be to simply load the user by email address, call $user->check_password($entered_password), and throw an exception/return false/whatever if check_password fails. Neither check_password nor any of the login handling code need to concern themselves with the database, or even with knowing that a database is where the user gets loaded from.
Another option is to think of the queries as data and store them in the database. For instance, you can create one table that stores the query with a name and another table that stores the parameters for that query. Then create a function in PHP that takes the name of the query and an array of params and executes the query, returning any results. You could also attach other metadata to the queries to restrict access to certain users, apply post-functions to the results, etc.

Categories