Before proceeding with the ADODB configuration, let’s first know what ADODB is and how it can help us.
ADODB stands for Active Data Object DataBase. And it is nothing more than an intermediate layer between PHP and the database managers.
ADODB provides a series of commands to standardize the connection to a database no matter which database manager we use (MySQL, Oracle, SQL Server, Sybase, among others).
The idea is to have the code related to the database connection, as well as the operations of select, insert, update and delete in functions. So they can be reused regardless of the programming language. These functions should be encoded with the ADODB commands so they can be executed in any database manager without changing any line of the code.
In this article, we will learn how to configure an ADODB connection from PHP to a MySQL database.
Good news, ADODB does not need to be installed. You just have to download the libraries from the official site and copy them to a folder where your server has access.
Do not worry if you do not have the ADODB libraries for MySQL you can download them from the official site: https://adodb.org/dokuwiki/doku.php?id=v5:database:mysql.
Set up a database connection
For purposes of this example, we must first create a contact table with the following structure and data:
After executing the above commands we must obtain the following table:
Now we can connect to our database and execute a query that returns the records of the Contacts table we just created.
To open a connection to the database via ADODB, we must create a PHP file with the following commands:
Then, if we open the PHP file in our browser we will see how the Contacts table content is displayed as we requested:
- Contact 1 data = 1 John 19005264555 firstname.lastname@example.org
- Contact 2 data = 2 Mary 19008504587 email@example.com
- Contact 3 data = 3 Matt 19006238747 firstname.lastname@example.org
- Contact 4 data = 4 Susan 19006781563 email@example.com
- Contact 5 data = 5 Carol 19007426336 firstname.lastname@example.org
If we look closely at the PHP code we will see 3 important commands:
newADOConnection : Creates the object that will manage the connection to the database
$database->connect : Opens the connection to the database
$database->execute : Execute the query we indicate
Portability of the ADODB code
As we mentioned at the beginning, portability is one of the advantages of ADODB commands. For the previous example, we only have to modify the parameter related to the database manager and we could use this same PHP code to connect to an Oracle database, SQL Server, Sybase, among others.