PHP to Azure SQL Server Undefined Function sqlsrv_connect - php

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:

Related

PHP PDO ODBC MSSQL connection

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

Could not connect to the database. Connector returned number: Database sqlsrv_connect failed

I am unable to connect Joomla to MSSQL
I keep getting
Could not connect to the database. Connector returned number: Database
sqlsrv_connect failed
Whether I use the MySQLi driver or the drivers I installed (Microsoft SQL Server)
Seems like driver installation issue ,
I am able to connect to the same box with Mssql Client fine...
Can someone post an explanation on how to install MSSQL drivers for Joomla on PHP from scratch?
Or send an up to date reference on how to do this?
Joomla 3.4
PHP 5.6
IIS 7.5
MSSQL 2008 R2
If I switch the driver to: php_sqlsrv_54_ts.dll - it will disperser from the "database type" in joomla installer..
Thank you
The joomla error that is displayed is misleading and not quite useful.
So first step would be to modify the joomla code to find out the exact error.
Modify the following code in connect() function in your application's root directory
libraries\joomla\database\driver\sqlsrv.php
From
// Attempt to connect to the server.
if (!($this->connection = # sqlsrv_connect($this->options['host'], $config)))
{
throw new RuntimeException('Database sqlsrv_connect failed');
}
To
// Attempt to connect to the server.
if (!($this->connection = # sqlsrv_connect($this->options['host'], $config)))
{
throw new RuntimeException("Database sqlsrv_connect failed - Error : ".print_r( sqlsrv_errors(), true));
}
This will give you the exact error and guide you with the next steps needed.
Another thing to consider during SQL server installation is to enable the SQL server authentication as Joomla uses SQL server authentication by default.
You can confirm that Joomla uses SQL server authentication by checking in the same function in the same file as mentioned above
$config = array(
'Database' => $this->options['database'],
'uid' => $this->options['user'],
'pwd' => $this->options['password'],
'CharacterSet' => 'UTF-8',
'ReturnDatesAsStrings' => true);
Here is the PHP manual that confirms the same.
http://php.net/manual/en/function.sqlsrv-connect.php
You can enable SQL server authentication either during installation or post installation from the manamgement studio.
Hope this helps.
Download SQLServer 2008 Express, SQLServer 2008 Standard/Enterprise
editions (R2 or later)
Download PHP Drivers
Download SQLSRV20.EXE to a temporary directory
Run SQLSRV20.EXE
When prompted, enter the path to the PHP extensions directory
If you are using some sort of LAMP stack like XAMPP
Copy php_sqlsrv_52_ts_vc6.dll to php/ext folder
Make an entry in php.ini as follows
Extension=php_sqlsrv_52_ts_vc6.dll
Note:
If you need PDO or vc9 versions - please copy the "ts" version
appropriate for your needs.
If you are using IIS with PHP engine installed via FAST-CGI - please
make the appropriate changes in c:\Program Files\php\php.ini and
copy the dll to c:\Program Files\php\ext folder
Now - You can install Joomla 2.5 by selecting the SQLServer 2008 from the dropdown list in the step 4 of the installation.
After installation is complete - continue navigation around the administrator/site

Making ODBC Driver 11 for SQL Server Available For PHP In Azure Website

I have a PHP 5.5 website running WordPress in Azure Websites configured to run with 64-bit IIS, with the database running in MySQL. I want to convert the site to use SQL Server in Azure instead of MySQL.
I've installed the WP Db Abstraction plugin, and followed its setup instructions. I've elected to use the sqlsrv driver, so I've installed the Microsoft Drivers for PHP for SQL Server 3.1 and added them into a folder in the WordPress website and configured them as an extension. Calling phpinfo() on a test page shows that the sqlsrv driver has been loaded into PHP, and also reports that PHP is x86.
I've also setup the database, user and password and tested that I can connect to it successfully using SQLCMD.
The Microsoft Drivers for PHP for SQL Server 3.1 instructions state that the "Microsoft ODBC Driver 11 for SQL Server version 11" is also required. I've downloaded the x64 and x86 versions and tried the DLLs out of the relevant Windows directories and added them to the extension directory alongside the PHP drivers for both architectures but neither has worked.
When trying to connect to the SQL Azure Database from the running PHP site, I just get this error:
This extension requires the ODBC Driver 11 for SQL Server. Access the following URL to download the ODBC Driver 11 for SQL Server for x86: http://go.microsoft.com/fwlink/?LinkId=163712
The DLL files for the drivers I have relative to the WordPress site root are:
ext\msodbcsql11.dll
ext\php_sqlsrv_55_nts.dll
ext\1033\msodbcsqlr11.rll
I have the following set in the Azure Management Portal for the website for the App Settings:
PHP_EXTENSIONS:ext\php_sqlsrv_55_nts.dll
All I can figure is that I'm either missing something from the ODBC drivers, or how I'm going about making them available to the PHP driver is incorrect.
Does anyone have any ideas as to what I've missed, or why this isn't working?
Below is the test code I'm using to test the SQL Server connectivity in PHP.
<?php
$serverName = "MYSERVER.database.windows.net,1433";
$connOptions = array("UID"=>"MYUSERNAME", "PWD"=>"MYPASSWORD");
$conn = sqlsrv_connect( $serverName, $connOptions );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
if( $client_info = sqlsrv_client_info( $conn)) {
foreach( $client_info as $key => $value) {
echo $key.": ".$value."<br />";
}
} else {
echo "Error in retrieving client info.<br />";
}
?>
I didn't really find a proper solution to this in the end, but it turned out that all the bits for using SQL Server with PHP 5.4 are already installed in Azure Websites.
I downgraded from PHP 5.5 to 5.4 and then SQL Server connectivity started working.
Not really a fix, but it's gotten me to the position (mostly) that I wanted.

Getting mssql_connect() error even though I have the drivers

this is something I've really been losing sleep over, so I'd be very thankful if anyone could help me.
So, I'm trying to set up a launcher for a game. I have a Login.php on my web server and the launcher in Visual Studio. When pressing "Start" it connects to Login.php where it checks if the game login credentials are correct, if they are, it should return a string of random letters (a token) to the Launcher. The Login.php tries to connect to my database in SQL Server 2008.
Now to the problem, I get
Fatal error: Call to undefined function mssql_connect() in C:\inetpub\wwwroot\Login.php on line 12
when trying to go to the website manually (By entering 127.0.0.1/Login.php into the browser.). And when I try to run the program and press start, it returns a 500 Internal Error.
I have googled the mssql error and found out that the mssql functions have been removed from the newer versions of PHP, so I downloaded the drivers from Microsoft and enabled them in the PHP Manager on IIS 7.5.
The version of PHP I use is 5.4.25 and I enabled these drivers:
php_pdo_sqlsrv_54_nts.dll
php_sqlsrv_54_nts.dll
And here are the first 13 lines of the Login.php:
<?php
$conf['db_host'] = "GERA044\SQLEXPRESS";
$conf['db_user'] = "sa";
$conf['db_pass'] = "L4sfa445AdxDDLfor95";
$conf['db_name'] = "Account";
$user = sql_clean($_GET['Username']);
$passhash = sql_clean($_GET['Password']);
$con = mssql_connect($conf['db_host'],$conf['db_user'],$conf['db_pass']) or die('Database connect Fail.');
$db = mssql_select_db($conf['db_name'], $con) or die('Database Init Fail.');
In short: I still get an mssql error even though I have the drivers.
Hopefully someone can find a solution to the problem here,
Thank you!
php_sqlsrv_54_nts.dll is the SQLSRV extension, not the MSSQL one. You should use the sqlsrv_* family of functions instead of the mssql_* one.

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.

Categories