Connect PHP through ODBC with DSN and DSN-less Connections

Last updated: August 25, 2026.

ODBC lets PHP connect through an installed database driver. A DSN stores driver and connection settings under a name; a DSN-less string supplies them directly in the application configuration.

Connect with a DSN

<?php
$connection = odbc_connect(
    'ReportingDatabase',
    $_ENV['ODBC_USER'],
    $_ENV['ODBC_PASSWORD']
);

if ($connection === false) {
    throw new RuntimeException(odbc_errormsg());
}

Use a DSN-less connection string

<?php
$dsn = 'Driver={ODBC Driver 18 for SQL Server};' .
       'Server=tcp:sql01.example.com,1433;' .
       'Database=Reporting;' .
       'Encrypt=yes;TrustServerCertificate=no;';

$connection = odbc_connect($dsn, $_ENV['DB_USER'], $_ENV['DB_PASSWORD']);
$statement = odbc_prepare($connection, 'SELECT name FROM customers WHERE id = ?');
odbc_execute($statement, [42]);

Checklist

  • Install a supported driver whose architecture matches PHP.
  • Keep credentials in environment or secret configuration, not source code.
  • Enable encryption and validate the server certificate.
  • Use prepared statements for application values.
  • Close result sets and connections in long-running processes.

PHP accepts both forms through odbc_connect().

admin

admin

Leave a Reply

Your email address will not be published.