65.9K
CodeProject is changing. Read more.
Home

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

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.22/5 (4 votes)

Jun 2, 2023

CPOL
viewsIcon

8165

downloadIcon

59

Having MSQL and ODBC connection string in one configuration file for your application

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
//--------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