Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / MySQL

PHP Sample of Database Connection Configuration File having Both Connection String for MySQL and MSSQL

1.22/5 (4 votes)
1 Jun 2023CPOL 8.2K   59  
Having MSQL and ODBC connection string in one configuration file for your application
This article is meant to show you how you can have connection string for MySQL Database and MSSQL Database in the same configuration file. At the end, you should be able to use this snippet on your database application. In one of my projects, I was able to use a similar approach. The config file was saved in the directory on the server and was called using require... in PHP.

Introduction

Nowadays, we can have applications which communicate with more than one type of database. And few or more people are worried about how to accomplish this. This snippet should show what you can do to be able to build a configuration file with two different database connection strings.

Background

I have used ODBC which is a low-level, high-performance interface that is designed specifically for relational data stores to be able to talk to MSSQL database. To be able to use the ODBC API, you will need to have ODBC driver. mysqli_connect() is used to connect to the mysql database.

Using the Code

To use this snippet, ensure to save it in PHP extension and have it located in your application folder depending on your application folder architecture. and on the page where it is needed, you can add this line require'./foldername/connection.php'; at the top of your queries:

PHP
<?php
//--------Connection with MSSQL Database
$server ="server IP";
$port="port";
$database ="database name";
$user ="username";
$pass="password";

$sqlsv='';
$connection_string = "DRIVER={SQL Server};SERVER=$server;$port;DATABASE=$database";
$sqlsv = odbc_connect($connection_string,$user,$pass);

//--------Connection with MYSQL Database
$servername = "server IP";
$username = "username";
$password = "password";
$db_name = "database name";

$conn1='';
$conn1 = mysqli_connect("$servername", "$username", "$password", "$db_name");

?>

Points of Interest

Good learning from here is that you do not need more than one file for all your database connection string. Your project can actually communicate with more than one database type.

History

  • 1st June, 2023: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)