Mysqli or custom database class?
I was wondering if a custom database class is really needed. I mean: I have seen a lot of datab开发者_如何学Pythonase abstraction layers and custom database classes all over the web. But why should we reinvent the wheel? Why shouldn't i use just the mysqli native class and extend it if i really need?
The mysqli class is secure, up to date and native. Why do people create their own classes with a query()
method, a fetch()
method and a free()
method while they already exists?
Mysqli has prepared statements too, it is one of the safest way to keep sql injection out of there.
It makes it easier to use the MySQLi extension. Using prepared statments with MySQLi is very cumbersome and requieres a lot of code, and you would duplicate the same basic code everywhere.
Whereas with a wrapper you can do stuff like this:
$rows = $db->Query ( '
SELECT
*
FROM
table_name
WHERE
field = ?
AND field2 = ?
',
Array (
Array ( 's', 'some val' ),
Array ( 'i', 42 )
)
);
you might also take an object oriented approach in accessing the data from your database. e.g. encapsulate all your data retrieval into an php class. and write all your data retrieval methods inside class functions using mysqli module
Writing the same repetitive code for common CRUD operations is cumbersome in plain SQL. See how Object-Relational Mappers approach this problem: Good PHP ORM Library?
精彩评论