从PHP访问数据库的最好方法是什么? [英] What is the best way to access a database from PHP?
问题描述
从PHP访问MySQL数据库时,有几种方法:
使用原始SQL语句
使用来自Java的VO模式(例如来自PEAR的DB_DataObjects)
DIY并编写一个脚本,每个数据库自动生成一个PHP类
除此之外,我还阅读了 LINQ在.NET
,但还没有看到它实现在 PHP。
其他模式有什么?
澄清:这不是关于DB抽象层(PDO,MDB2)。这里讨论的模式是你在PDO或MDB2上构建的。
我会选择来自PEAR的MDB2数据库抽象层 - 它提供了一个很好的,抽象的方法来处理数据库。我推荐它,因为它允许你编写可移植代码,可以移植到不同的数据库服务器,而不需要做许多更改(对于基本脚本,只是更改连接调用可能是足够的)。它是旧的DB和Metabase抽象层的合并(DB仍然支持错误修复,但已被MDB2取代)。
它提供的功能,如准备+执行仿真DB不正确地支持它,并允许您使用占位符,这是一个好的做法,以避免SQL注入问题。 / p>
它将使用:mysql / mysqli,pgsql(PostgreSQL),oci8(Oracle),sqllite,msql,mssql(Microsoft SQL Server),sybase,informix,fbsql, ibase,odbc。
请查看 MDB2 documentation ,看看它是如何工作的。
When accessing a MySQL-database from PHP there seems to be several ways:
Sprinkle the code with raw SQL-statements
Use the VO-pattern from Java (e.g. DB_DataObjects from PEAR)
DIY and write a script that auto-generates one PHP class per database
Apart from this I have also read about LINQ in .NET
but have not seen it implemented in PHP.
What other patterns are there?
If you started building a website from scratch today, which one would you choose?
Clarification: This is not about DB abstraction layers (PDO, MDB2). The pattern discussed here is something you build upon PDO or MDB2.
I'd choose the MDB2 database abstraction layer from PEAR - it provides a nice, abstracted method to deal with the database. I recommend it, since it allows you to write portable code which can be ported to a different database server without many changes required (for a basic script, just changing the connect call is likely to be sufficient). It is a merge of the old DB and Metabase abstraction layers (DB is still supported for bugfixes, but has been superceded by MDB2).
It offers features like prepare + execute emulation for DBs that don't support it properly, and allows you to use placeholders which is good practice to avoid SQL injection problems.
It will work with: mysql / mysqli, pgsql (PostgreSQL), oci8 (Oracle), sqllite, msql, mssql (Microsoft SQL Server), sybase, informix, fbsql, ibase, odbc.
Have a look at the MDB2 documentation to see how it works.
这篇关于从PHP访问数据库的最好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!