写PHP代码支持MySQL和PostgreSQL,不使用OOP或PDO。

huangapple go评论64阅读模式
英文:

Write PHP code support both MySQL and PostgreSQL without OOP or PDO

问题

以下是已翻译的内容:

我想用PHP编写一个简单的论坛网站,可以配置为使用MySQL或PostgreSQL。目前有PDO,但我不懂面向对象编程,也不想学它。我有一个关于服务器软件的参数的想法,可以使用mysqli或pgsql扩展。例如:

function db_connect($mysql = null, $hostname, $username, $password, $database, $software) 
{
  switch ($software) 
  {
  case "mysql":
    return mysqli_real_connect($mysql, $hostname, $username, $password, $database);
  case "pgsql":
    return pgsql_connect("host=$hostname, port=5432, dbname=$database, user=$username, password=$password");
  }
}

这是一个好主意吗?目前我还不需要太多功能。

英文:

I wanted to write a simple forum site with PHP that can be configured to use MySQL or PostgreSQL. Currently there are PDO, but I don't know OOP and I don't want to learn it. I have an idea about a function that take an argument about server software, and use either the mysqli or pgsql extension. For example:

function db_connect($mysql = null, $hostname, $username, $password, $database, $software) 
{
  switch ($software) 
  {
  case "mysql":
    return mysqli_real_connect($mysql, $hostname, $username, $password, $database);
  case "pgsql":
    return pgsql_connect("host=$hostname, port=5432, dbname=$database, user=$username, password=$password");
  }
}

is that a good idea? Currently I don't need much functions to work yet.

答案1

得分: 3

不行,那行不通。如果你真的尝试了那段代码,你就会知道。

这是因为 mysqlipgsql 有着非常不同的库API,并且几乎没有共享的函数调用。即使你使用PDO作为通用的数据库API,你仍然会遇到大多数查询在这两者之间不兼容的问题。PDO的目的不是让你可以针对任何后端使用相同的查询,而是让你不必在每次需要使用不同的数据库后端时学习不同的数据库库API和工作流程。

如果你想要开发一个支持不同数据库后端的应用程序,那么你需要在应用程序和数据库之间建立一个“抽象层”,来处理每个数据库的查询语法和特殊之处。许多框架使用ORM或类似的技术来实现这一点。

英文:

No, that won't work. If you actually tried that code you'd know.

It's because mysqli and pgsql have vastly different library APIs and share virtually no function calls. Even if you did use PDO as a common DB API you would still have problems with most queries not being compatible between the two. The point of PDO is not so that you can use one query against any backend, it's so that you don't have to learn a different DB library API and workflow every time you need to use a different DB backend.

If you want to have an application that supports different DB backends then you need an abstraction layer between your application and the database to handle the query syntax and peculiarities of each. Many frameworks use an ORM or similar technique for this.

huangapple
  • 本文由 发表于 2023年7月6日 13:09:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76625679.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定