连接Azure SQL Server时出现PDOException找不到驱动问题求助
Problem Description
I'm getting this exception when trying to connect to Azure SQL Server:
PDOException Object ( [message:protected] => could not find driver )
At first, I thought the issue was the pdo_mysql extension wasn't enabled, but I checked my php.ini and confirmed it's active—plus all my other Laravel projects using MySQL connect just fine, and phpinfo() shows pdo_mysql is installed.
Here's the PHP code I'm using to connect to Azure SQL Server:
$sqlServer = "tcp:server.database.windows.net,1433"; $sqlUser = "admin@server"; $sqlPwd = "password"; $sqlDb = "database"; $sqlDsn = "sqlsrv:Server=$sqlServer;Database=$sqlDb"; try { $conn = new PDO($sqlDsn, $sqlUser, $sqlPwd); $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); } catch (PDOException $e) { die(print_r($e)); }
I've double-checked that my credentials are correct (I modified them here for privacy). Can anyone help figure out why I'm still getting the "could not find driver" error?
Answer
Oh, I see the key issue here—you're mixing up PDO drivers for MySQL and SQL Server! The pdo_mysql extension only works for MySQL databases, but Azure SQL Server requires the pdo_sqlsrv driver entirely. Here's how to fix this:
First, check if
pdo_sqlsrvis installed
Pull up yourphpinfo()page and search forpdo_sqlsrv. If you don't see this section at all, that means the driver isn't installed on your system.Install the correct driver based on your OS
- Windows:
- Download the SQL Server PHP extensions matching your PHP version (e.g., 8.1, 8.2) and system architecture (x86/x64). You'll need both
php_sqlsrv.dllandphp_pdo_sqlsrv.dll. - Drop these files into your PHP extensions folder (usually the
extfolder inside your PHP directory). - Open
php.iniand add these two lines:extension=sqlsrv extension=pdo_sqlsrv - Restart your web server (Apache, IIS, Nginx—whichever you're using).
- Download the SQL Server PHP extensions matching your PHP version (e.g., 8.1, 8.2) and system architecture (x86/x64). You'll need both
- Linux (Ubuntu/Debian):
- Install the extensions via PECL:
pecl install sqlsrv pdo_sqlsrv - Add the same extension lines to your
php.inifile, then restart your web server.
- Install the extensions via PECL:
- Windows:
Verify the driver is working
After restarting, refresh yourphpinfo()page—you should now see apdo_sqlsrvsection with details about the installed driver. Run your connection code again, and it should connect without the driver error.Quick note for Laravel users
If you're using this in a Laravel project, make sure your.envfile hasDB_CONNECTION=sqlsrvinstead ofmysql, and double-check the other database credentials match your Azure SQL Server details.
内容的提问来源于stack exchange,提问作者Collin

