0

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.

  • 6
    _I don't want to learn it_ Learning is the only constant thing in the IT industry. – nice_dev Jul 06 '23 at 05:35
  • 2
    Being unwilling to learn things is a dealbreaker in pretty much _any_ industry, tbh. All of the worst coworkers I've ever had were the type that had already learned "everything that they needed to know" 5+ years ago and then just stagnated both professionally and personally. – Sammitch Jul 06 '23 at 05:42
  • 2
    OO is the foundation of a lot of modern industry-standard programming languages. Take the opportunity. It will make your life easier in the long run because the code you write will, if you make a decent job of it, be easier to understand, test, maintain and re-use – ADyson Jul 06 '23 at 05:51
  • 1
    It will work, for some definitions of to work. You'll essentially build two entirely different application engines, each one with its own connections, SQL, etc. But they'll be completely interleaved. You'll trade learning time for maintenance time. – Álvaro González Jul 06 '23 at 07:02

1 Answers1

3

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.

Sammitch
  • 30,782
  • 7
  • 50
  • 77