开发者

Accessing DB via function vs object, difference? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

PHP PDO vs normal mysql_connect

So in my application, I accessed the database via a function named db_connect();. Quite simply, it fed the requisite login information and opened a database connection via mysql_conn开发者_开发知识库ect and mysql_select_db.

Now that I'm working, I have found that the lead programmer uses PDO. Fancy. However, it looks more or less like an object-oriented version of the same thing I used to use.

So what's the difference between doing it the way I used to, or writing a class "db" with a constructor that automatically connects to the database?

In both cases, I'd have to connect to the db/create a new object, which, in either case, takes up one line.

Is it a fancy library to abstract away the nitty-gritty of database connections?

The only thing I can think of is that there's a destructor in the OO version, which means I wouldn't have to code in a "db_close()"...

Edu-ma-cate me! (Please'm)


Whether your database library is functional or object oriented is not really relevant per se, but PDO is very modern and has a number of advantages over plain old mysql_connect() and consorts, most importantly parametrized queries that make SQL injections impossible.

Also, PDO supports a whole lot more database platforms.

From an architectural perspective, the OOP approach also makes sense, it's more than just decoration: You create a PDO object, which is your database connection. Multiple objects = multiple connections. Wrapping a result set into an object - providing all the functions to fetch rows, skip, rewind, etc.... is also very logical.

If I were to choose a database wrapper for a new project, I'd definitely go with PDO over mysql_*().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜