I'm pretty new to FuelPHP.
My first question is what is the best place to put custom functions? Right now, I just made a new file, func.php, inside the app/classes folder and access it like $func = new Func; $func->function_name(); - I don't think this is the best way to do it.
Secondly, for something I'm making, I'll be needing a lot of custom queries. Normally, I'd just use PDO's prepared statements and execute them, but I'm unsure how I'd go about sanitizing user input with DB::query(), without having to sanitize each individual variable.
Autoloading function is not possible with PHP, so many people use classes, like you did... More information is available in this SO anwser: Autoloader for functions
For prepared statements, you got that: http://docs.fuelphp.com/classes/database/usage.html#binding
You still can use plain old PDO if you want, it's totally possible.
Related
My web project has a class called DB_CONNECTOR where all the functions are bundled that interact with the mysql database. These would be functions like get_user(), add_user(), change_user_attribute() and many more. In each of these functions a sql query is executed and as is good practice, I use prepared statements (with named parameters).
Currently the connection to the database is established in the constructor of the class and also all the statements are prepared there. I thought this would be a good idea, so the statements are all immediatly ready for execution.
Now I realized that my use case is often to create a db_connector object, execute one or maybe two functions and then the objects lifecycle ends and at a later step a new one might be constructed (or not). So, I'm not so sure anymore if it smart to put the prepared statements in the constructor as it is forseeable that I will end up with at least 20 or likely more prepared statements.
So my question is:
is it a good idea to prepare all the statements in the constructor even if only one or two are used?
Or should I prepare them in the functions right before execution to avoid stressing the db with unneeded preparations?
This answer is based in both my experience and humble opinion, but I'll try to elaborate my arguments so it isn't just some random guy's opinion.
I don't think the database connection must be the core object in your application, let alone the only one. It'd expect to see an entirely different class for the user, so you can later have further classes for everything else. Otherwise, your application will eventually consist of a single class in a 5000 line file and your class will not be suitable to track entity data at instance level and you'll need to pass variables around in method calls. That's pretty much procedural code in OOP dress.
Also, I don't that making your User class inherits from Database (something pretty frequent nonetheless) is practical at all. Interlacing the database connection and the business logic objects doesn't really simplify application design and actually makes some parts harder.
The design of the database layer itself is pretty much standardised:
One connection per application (or more... you may need to connect to several sources!)
One statement per query.
This is exactly how PDO works.
Given that, it's easier to make the database classes just one more dependency of your entities rather than their grandparent. The injection of this dependency can be done by different means:
Make it a class property:
public function __construct(\PDO $connection)
{
$this->connection = $connection;
}
Pass it to the methods they actually needed (if not many of them):
public function getOrders(\PDO $connection)
{
$stmt = $connection->prepare('SELECT ...');
}
... or use one of those fancy dependency injection containers you can find at Packagist.
Be aware that there're also object-relational mapping (ORM), active record pattern... Those are entirely different families of solutions which may suit your needs or not depending on your use case, but not what I'm describing here.
Said that, it becomes obvious that you prepare the statements at the exact point where you need them. This design doesn't even allow otherwise ;-)
I have found a few guides like this http://www.mackhankins.com/blog/defining-your-own-helper-classes-in-laravel-4 but it isnt really what im looking for as i want to be able to use functions to modify values that arent members of a class.
I have a lot of regex functions that will modify strings if they match a pattern and return a modified string. I want to be able to call these functions as if they were built in php functions. is what i would have always done in the past, but i want to do this right.
This post What are the best practices and best places for laravel 4 helpers or basic functions? seems to be getting closer, but im still not clear on why i would have to instantiate an object just to run a basic function.
Just plop all your custom functions in a file names something like "helpers.php". You don't need to do anything special.
You could either directly include the file in your bootstrap file or just set composer up to auto-load it.
I have heard, (thanks to SO) that mysql_* family of functions is vulnerable to SQL injections, so it is always recommended to use mysqli_* OR PDO approach.
So, I tried to trace out which of these approaches is used in Codeigniter as I have been using CI since 4 months. But I could not get it out.
Can anybody tell me which of these or any other approach is used in CI?
Thanks in advance.
CodeIgniter uses whichever method you choose, based on your config/database.php file. For example, if you choose mysqli as your driver, it will use the mysqli family of functions. If you choose mysql, it will use the mysql family, and so on.
There is a PDO driver, but it's not the most stable thing in the world in the current releases.
If you're using the "active record" functions in CodeIgniter (which should really be called "query builder" functions, since they don't follow the Active Record pattern), then all of your data is automatically sanitized with the appropriate functions. If you say, for example, $this->db->where('field', $value), and you're using the mysqli driver, CodeIgniter will automatically call mysqli_real_escape_string on the $value input you pass to it, rendering the query safe.
I should also note that this automatic sanitization only applies to the active record helper functions, like $this->db->get and the like. If you try to run your own query using $this->db->query("SELECT * FROM table WHERE field = '" . $field . "'") then you need to take care to protect yourself, since you're bypassing CodeIgniter's security mechanisms. Running a query directly with the query() method is like saying "don't worry, I know what I'm doing." You need to specifically ask CodeIgniter to sanitize certain values for you by calling $this->db->escape() or its related functions. If you just concatenate variables into your query, then you're going to open yourself up to SQL injections.
So as many already know the $wpdb class in Wordpress can't deal with inserts and updates involving NULL values. This is a major headache, and there doesn't seem to be a good way around it.
So I'm wondering what the next best way is to insert/update tables in Wordpress? I liked WPDB cause of the prepared statements, so I was hoping to have something where I could continue with that. Unfortunately, no PDO support?
Any suggestions?
Here is a solution for Null values, just create a new class by extending the wpdb class and use two new insert and update functions and to do this you can create a db.php file in your wp-content directory and drop this content in the file.
Not tested but you may give it a try.
Can anyone recommend a good wrapper class or extension to PHP's mysqli extension that allows the equivalent of
mysql->fetch_assoc()
for a prepared statement. That is ideally it condenses down into a single statement the tedious complexity of the init/prepare/bind/fetch-loop.
try dalmp.com code.dalmp.com currently on beta but maybe you can help to test it
Write a class that extends mysqli and adds that functionality!!!!
Here's a start
http://us.php.net/manual/en/mysqli-stmt.fetch.php#72720
This is PHP 5 class that does just that: http://www.aplweb.co.uk/blog/php/mysqli-wrapper-class/
Just put in your settings and call one of the static functions.
It's actually really easy to write wrappers for or extend PDO.
$this->setAttribute(self::ATTR_STATEMENT_CLASS, array('yourClassName', array($this)));
Something like that will let you specify a class to replace PDOStatement.
Zend_DB is a great wrapper for database functions including mysqli.
It has options to retrieve table data as associative arrays, or as objects if you desire. It also includes support for prepared statements.
You don't have to use the entire zend framework to use Zend_DB, you can use it on its own.