0

I was wondering if a custom database class is really needed. I mean: I have seen a lot of database 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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Shoe
  • 74,840
  • 36
  • 166
  • 272

3 Answers3

1

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 )
  )
);
Jan Hančič
  • 53,269
  • 16
  • 95
  • 99
  • And why should this be so much better than $stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)"); $stmt->bindParam(':name', $name); $stmt->bindParam(':value', $value); – Shoe Nov 20 '10 at 11:32
  • Because there is a lot more code to it than what you have posted. – Jan Hančič Nov 20 '10 at 11:34
  • Yep but way a lot more flexibility too. With your function you can just create direct queries without actually being able to use the power of prepared statements (declare a statement and use it multiple times). – Shoe Nov 20 '10 at 11:38
  • Sure you can, that was just an example. In my class `Query` actually returns a prepared statement, I also have a `GetRows` method that returns an array with rows. So you can decide which one to use ... – Jan Hančič Nov 20 '10 at 11:41
0

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

Troydm
  • 2,642
  • 3
  • 24
  • 35
0

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?

Community
  • 1
  • 1
bcosca
  • 17,371
  • 5
  • 40
  • 51