PHP PDO ODBC MSSQL connection - php

I've installed PHP on IIS7 following the official PHP documentation and it succeed. I can run PHP files and my site is OK.
But I can't connect to my database on MSSQL with PDO and ODBC driver. I've set my php.ini carefuly and I think all is good. Morever I also think ODBC is native on Windows and PDO is included in latest PHP builds (mine is 5.5.36).
So here's my connection code :
define("UID", 'uid');
define("PWD", 'pwd');
define("DSN", 'odbc:decheterie');
// where 'decheterie' is the dataSource set in the ODBC Connection Manager
try {
$pdo = new PDO(DSN, UID, PWD);
} catch (PDOException $e) {
die("Error! ".$e->getMessage());
}
The error I get is :
Error! Could not find driver
If I run a php -m I can see that PDO and ODBC modules are correctly loaded.
But a PDO::getAvailableDrivers() returns an empty array and it can be verified within the phpinfo() which displays 'no value' in the 'PDO drivers' section.
I've read a lot of posts and articles and each time a response is valided as 'problem solving' it's already good in my config.
If someone can help it will be blessed ;)

Solved!
The answer is in the above comments. You need to DL the php_pdo_sqlsrv_*.dll
in your PHP /ext folder and references it as an extension in your php.ini
The '*' is for the PHP version everything is well described in the
MSDN doc here
Thanks

Related

PHP to Azure SQL Server Undefined Function sqlsrv_connect

I've been trying to connect to my Azure SQL database using PHP 7.1. I've been following Microsoft's instructions so I'm using the iis express. After browsing and following the directions from posts like "Call to undefined function sqlsrv_connect()" when trying to connect to Azure DB from PHP and
Cannot Call function sqlsrv_connect(), I still cannot connect.
<?php
$serverName = "database_name.database.windows.net";
$connectionOptions = array("Database" => "database_name");
try {
$conn = sqlsrv_connect($serverName, $connectionOptions);
} catch (Exception $e) {
print_r($e);
}
?>
Here are the solutions I've tried:
Installed all the necessary SQL drivers
Reconfigured the php.ini file with the extensions and correct extension path
Ran PHP as an administrator from the PHP folder and also from another folder using its %PATH%
Restarted several times
Connected successfully to the database from the CMD line
This is my first time using PHP to connect to a remote SQL server so any help would be greatly appreciated.
You need to check whether your drivers match the PHP Version, Architecture (32/64 bits) and Thread Safety you are using.
For example, if you are using x86 and thread-safe version of PHP 7 then the following DLLs should be used:
extension=php_sqlsrv_7_nts_x86.dll
extension=php_pdo_sqlsrv_7_nts_x86.dll
You can see these PHP info via phpinfo() function:

How to do I connect to a SQL Server instance from PHP 7 on an AWS Amazon Linux EC2 instance?

I have Apache 2.4 and PHP 7 installed and working fine on an Amazon Linux AMI on AWS. From PHP, I can connect to MySQL DBs just fine, but now I need to connect to a SQL Server DB.
How do I do this? What's the PHP code I need to write and do I need to install additional PHP packages/modules to do this? I already have PDO installed and tried to use it, but the following code throws the following error:
$dsn = 'sqlsrv:dbname=db-name;host=aws-endpoint.rds.amazonaws.com';
$user = 'user-name';
$password = 'password';
$dbh = new PDO($dsn, $user, $password);
Error:
PHP Fatal error: Uncaught PDOException: could not find driver in /var/www/html/php-script-name.php
Edit: Adding to my question a bit, I ran a yum search pdo from the EC2 instance and got the following:
Loaded plugins: priorities, update-motd, upgrade-helper
============================================================================================================= N/S matched: pdo ==============================================================================================================
php-ZendFramework-Db-Adapter-Pdo.noarch : Zend Framework database adapter for PDO
php-ZendFramework-Db-Adapter-Pdo-Mssql.noarch : Zend Framework database adapter for MS SQL PDO
php-ZendFramework-Db-Adapter-Pdo-Mysql.noarch : Zend Framework database adapter for MySQL PDO
php-ZendFramework-Db-Adapter-Pdo-Pgsql.noarch : Zend Framework database adapter for PgSQL PDO
php70-pdo-dblib.x86_64 : PDO driver Microsoft SQL Server and Sybase databases
php71-pdo-dblib.x86_64 : PDO driver Microsoft SQL Server and Sybase databases
php-pdo.x86_64 : A database access abstraction module for PHP applications
php54-pdo.x86_64 : A database access abstraction module for PHP applications
php55-pdo.x86_64 : A database access abstraction module for PHP applications
php56-pdo.x86_64 : A database access abstraction module for PHP applications
php70-pdo.x86_64 : A database access abstraction module for PHP applications
php71-pdo.x86_64 : A database access abstraction module for PHP applications
Name and summary matches only, use "search all" for everything.
It seems like php70-pdo-dblib.x86_64 is the plugin I want, so I ran yum install on it and my phpinfo now looks like the following:
I did restart Apache as well, but I still get the error noted above with the code noted above.
As such, I do not think that this is a duplicate of the question linked in the comments section.
I figured it out. You do in fact have to have php70-pdo-dblib installed and restart the server. However, my $dbn string was off. Specifically, sqlsrv needed to be changed to dblib and I added the port number :1433 onto the end of the host part.
As such, the following code worked:
$dsn = 'dblib:host=aws-endpoint.rds.amazonaws.com:1433;dbname=db-name;';
$user = 'user-name';
$password = 'password';
try {
$dbh = new PDO($dsn, $user, $password);
$result = $dbh->query("SELECT *
FROM table-name;");
foreach ($result as $row) {
echo '<pre>';
print_r($row);
echo '</pre>';
}
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
You need to install the Microsoft SQL PHP driver.
Follow the instructions on this page:
MSPHPSQL
Follow the official guide from Microsoft when you get to the point of installing unixODBC refer to this page to build an RPM and install it:
https://github.com/EreMaijala/unixODBC

Windows 8.1 PHP PDO connection issues again

This is the common error often reported in questions:
SQLSTATE[IM002] SQLDriverConnect: 0 [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
Please assume correctly that I've been reading posts for ... 'days'!
I've done all the following:
1) Uncommented: extension=php_pdo_odbc.dll in php.ini
2) Set-up a system DSN in SysWOW64\odbcad32.exe
3) Checked that odbcjt32.dll is present in SysWOW64
My standard (latest PHP) code:
if (!file_exists($dbName)) {die("Could not find database file.");}
try {
$dbh = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=$dbq;Uid=$user;Pwd=$password");
}
catch (PDOException $e)
{
echo $e->getMessage();
}
There is no file_exists error (so addressing isn't the issue)
The .mdb is mine (so I know the correct Uid/Pwd)
The .mdb is in the same inetpub folder as the .php file calling it (so not permissions)
In windows powershell, I've run: Get-OdbcDsn which correctly shows the rich1 system DSN:
Name : rich1
DsnType : System
Platform : 32-bit
DriverName : Microsoft Access Driver (*.mdb)
Attribute : {DBQ, DriverId, ImplicitCommitSync, Threads...}
Still the same error :-( so I'm dead ended.
Does anyone know of any more 'Get-OdbcDsn' type routines that will help diagnose what's going on? Or any kind of new tack that leads me away from this dead end?

How can I use PDO with MSSQL in PHP from a Windows dev envirenment?

I am developing an application that needs to get data from an outside MSSQL database. I spent a lot of time trying to get various methods of connection to MSSQL with PHP, but there were several routes which were depreciated.
On my production environment running Debian, I was able to make a connection with PDO_DLIB and FreeTDS with something like this:
$this->db = new \PDO('dblib:host='.$thedb_host_prod.';dbname='.$thedb_database_name_prod, $thedb_database_user, $thedb_database_pass);
On Windows, MSSQL is depreciated. I believe I'm using the Microsoft SQL Server Driver and was only able to get it to work with ODBC, which looks something like this:
$dsn = "Driver={SQL Server};Server=".$thedb_host_dev.";Database=".$thedb_database_name_dev;
$this->odbc = odbc_connect($dsn, $thedb_database_user, $thedb_database_pass);
Then, the problem becomes, in each method I need to do something differently for ODBC than I do for DLIB.
public function exampleMethod(){
// logic and create the query in $query
if($this->dev == false){
// PRODUCTION
try {
$stmt = $this->db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
} else {
// DEVELOPMENT
$query = $query;
$stmt = odbc_exec($this->odbc, ($query));
$result = array();
while($currentRow = odbc_fetch_object( $stmt )){
$jobNumber = $currentRow->Code; // Set object key to jobNumber
array_push($result, $currentRow);
}
}
}
This actually works, but the problem is, with how the query for ODBC needs to be prepared vs how the DBLIB query should be prepared, means that if I don't want to write the query twice in each method, I have to create it before each action. This is really bad because it means I'm not putting my variables into the query with PDO's bindValue.
So, has anyone been able to get PDO work with PHP 5.4 and MSSQL in a Windows environment? Does anyone see a way of securing the query in a way that doesn't make me duplicate the query in each method, once for ODBC and once for DBLIB?
My plan currently is to develop the application out and then remove all of the ODBC stuff which will allow me to put the query in the $stmt properly, avoiding this problem. But until then, it's making development a huge pain.
Oooook, so I finally got it working !
Here are the libraries / drivers for Sql-server connection via C/C++/java/PHP/etc.
Precisely, here are the Windows drivers for PHP.
Check out this page to know which version you need to get
They all exist in have 32 and x64, as well as "Thread safe" (ts) and "non-thread-safe" (nts) versions.
From what I read, nts versions are to be used if you work with IIS.
Usage :
Download and extract the package you need.
in my case, package 3.2, for php 5.6
Take necessary drivers
in my case, php_sqlsrv_56_ts.dll and php_pdo_sqlsrv_56_ts.dll
Put them in your php extensions directory
in my case, [...]\php5630vc11x86x170623162800\ext
If you wonder where this dir is inside your PHP, it should be quite easy to find, since you have plenty of other dlls here.
Likely, php_pdo_mysql.dll, php_pdo_pgsql.dll, etc.
Modify your php.ini
Be careful with Wamp, it seems to have one in the php directory AND another one in the apache dir.
Add lines to load the two extensions.
You can add them at the end of your file, or with the other extensions loading.
In my case, here's what I added :
;SQL-srever extensions
extension=php_sqlsrv_56_ts.dll
extension=php_pdo_sqlsrv_56_ts.dll
This part was for the PHP/PDO side.
For the driver to actualy work, you also need your (Windows) machine to have the ODBC drivers installed.
Feel free to try your connection already, but if it whines that you need the ODBC driver, go get it here :
Microsoft® ODBC Driver 11 for SQL Server®
And last, but not least, be sure to use the right format for your PDO connection.
$conn = new PDO ("sqlsrv:Server=$srv_host;database=$srv_dbname";
For comparison, here's what I wsa using on my linux server :
$conn = new PDO ("dblib:host=$srv_host:$srv_port;dbname=$srv_dbname", "$srv_username", "$srv_password");
I thought this syntax was common to all PDO drivers, but it appears I was wrong.
Here is the PHP PDO driver documentation.
I just actually had to do some work in php connecting to a MSSQL server. I did have to downgrade to php 5.4 due to the fact that the php_pdo_sqlsrv.dll is not updated for 5.5. For the dll files check here. But now down to the code I used to connect once you have the .dll files in the right place.
try {
$db = new PDO("sqlsrv:Server={$host};Database={$database}", $userName, $password);
}catch(PDOException $e){
die("failed to connect");
}
Just a standard PDO connection. Just in order to get it to work you must make sure that the .dll files are in the php directory.
I hope that answers at least part of the question.
I have worked with PHP 5.4 and SQL Server with PDO on Windows.
I strongly recommend using Microsoft's Web Platform Installer to set everything up. You can use it to install PHP, a local version of SQL Server Express to develop on, the official PHP driver for SQL Server, and IIS, all set up to work together.
One note of caution: The last release of the SQL Server PDO driver was in April, 2012. I reported a bug against it last year and was told that it's in "limited support", which apparently translates to "you're on your own". In any case, it worked reasonably well.

MSSQL PDO could not find driver

I'm using PHP Version 5.3.8 that was installed via XAMPP along with Microsoft SQL Server 2008 R2 (SQLEXPRESS). I have the drivers installed correctly (i guess) and have added the correct line into php.ini (extension=php_pdo_sqlsrv_53_ts_vc9.dll to be exact).
I'm trying to connect to the server like so:
try {
$DBH = new PDO("mssql:host=xxxx;dbname=xxxx", 'xxxx', 'xxxx');
} catch(PDOException $e) {
echo $e->getMessage();
}
I get the "could not find driver" error, and I've tweaked it all kinds of ways to solve the problem. I've tried all other kinds of drivers, but this is the only one that Apache doesn't give me an error on startup. When I run phpinfo(), the pdo_sqlsrv fields are all blank except pdo_sqlsrv.log_severity which is set to 0.
I DL'd my drivers from microsoft, and I've tried both 2.0 and 3.0
Any advice would be awesome!!
mssql is the old way of doing it, sqlsrv should be more appropriate! In fact the extension is called (extension=php_pdo_sqlsrv_53_ts_vc9.dll) as well ;)
try {
$DBH = new PDO("sqlsrv:Server=xxxx;Database=xxxx", 'xxxx', 'xxxx');
} catch (PDOException $e) {
echo $e->getMessage();
}
Hope this helps!
Source : http://php.net/manual/fr/ref.pdo-sqlsrv.connection.php
Not sure if this is due to running a CentOS x86_64 machine but sqlsrv didn't work as the driver for me, I had to use dblib:
try {
$DBH = new PDO("dblib:host=xxxx;dbname=xxxx", 'xxxx', 'xxxx');
} catch (PDOException $e) {
echo $e->getMessage();
}
Source and thanks to.
as I said in this
please notice you must use the correct version of php_sqlsrv_xx_xts_xxx.dll and php_pdo_sqlsrv_xx_xts_xx.dll files.
for exmple if you use php version 7.4 and a 64 bit system and wamp you must download and use these files:
php_sqlsrv_74_ts_x64.dll
php_pdo_sqlsrv_74_ts_x64.dll
for download you can use this site:
https://go.microsoft.com/fwlink/?linkid=2152937
https://learn.microsoft.com/en-us/sql/connect/php/download-drivers-php-sql-server?view=sql-server-ver15

Categories