How to Connect Joomla with an SQL Server?

Author:

In the Joomla database connection implemented in the configuration.php file. But if you want to create a connection in the external file of the Joomla setup then you can do it as well. So in this post, you will learn How to connect Joomla with an SQL Server?

Generally, Joomla uses a MySQL server for the database. In this post, you will learn How to connect Joomla with an SQL Server.

Let’s See: How to Change Joomla Database Prefix in Joomla 4?

How do you Connect Joomla with a MySQL Database?

Let me share the code below-

$option = array();
$option[‘driver’] = ‘sqlsrv’;
$option[‘host’] = ‘server’;
$option[‘user’] = ‘user’;
$option[‘password’] = ‘pass’;
$option[‘database’] = ‘db’;
$option[‘prefix’] = ”;
$db = &JDatabase::getInstance($option);
$query = $db->getQuery(true);
$query = “SELECT * from Test”;
$db->setQuery($query);
$results = $db->loadObjectList();

Let’s See: Joomla 4 vs Joomla 3 – What’s the New Features in Joomla 4?

Joomla Database Connection variables

First of all $option is an array variable that contains 6 array variables.

  • Driver: it’s using the database driver type like MySQL (mssql) or SQL server(sqlsrv).
  • Host: it’s using the hostname of the server (localhost)
  • User: it’s using the username of the database.
  • Password: it’s using the password of the database.
  • Database: it’s using the “db” as a value for this variable.
  • Prefix: it’s the database table prefix, so what prefix will be used with the database table name will be used here?

$db = &JDatabase::getInstance($option);

The above code creates a connection to Joomla with SQL Server. If everything is correct then it will return true otherwise false to the $db variable.

You can check what value is coming in the “$db” value by using the following statement of code:

If($db== true){

$query = $db->getQuery(true);

$query = “SELECT * from Test”;

$db->setQuery($query);

$results = $db->loadObjectList();

}else{

echo “Database connection failed!”;

die();

}

So if the $db variable returns the true then you can write database queries like SELECT, UPDATE and DELETE.

In the above code, I have written a SELECT query to fetch data from the “Test “ database table.

Learn about: How to update Joomla to the latest version