Search code examples
phpmysqliphp-pgsql

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


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.


Solution

  • 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.