sqlsrv_connect attempt doesn't succeed or fail - php

I'm attempting to connect to a MS SQL Server via PHP7 sqlsrv driver.
It seems like when my browser tries to execute:
$conn = new PDO( "sqlsrv:Server=$serverName;Database=mydb", $uname, $pass);
or
$conn = sqlsrv_connect( $serverName, $connectionInfo);
it just hangs. No success or failure echo/die messages are received. Instead, the wheel in my browser keeps spinning and the status message is "waiting for localhost". It also doesn't seem to ever timeout. I've waited 10+ minutes and the connection never fails/succeeds.
Full code (I've tried procedural and PDO methods):
<?php
//
$serverName = "myserver\myinstance"; //serverName\instanceName
$uname = "myuser";
$pass = "mypass";
$connectionInfo = array( "Database"=>"mydb", "UID"=>$uname, "PWD"=>$pass);
/*Procedural sqlsrv method
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
die("DONE");
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
*/
/*PDO sqlsrv method*/
try {
$conn = new PDO( "sqlsrv:Server=$serverName;Database=mydb", $uname, $pass);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
die("success!");
} catch(PDOException $e) {
die($e->getMessage());
}
?>
Setup details and other information:
I'm using XAMPP.
Windows 7 x64
PHP 7.0.9
I'm trying to connect to an instance of Microsoft SQL Server version 10.50.6220.0 on a Windows NT machine
I need to authorize via SQL Server Authentication -- not Windows Authorization
I'm able to successfully connect to the database using Microsoft SQL Server Management Studio and other tools (FME Workbench)
The server is remote, but is accepting remote connections (as verified with SSMS)
I previously had issues with "undefined function sqlsrv_connect()" until I installed
php_sqlsrv_7_ts_x86.dll
and
php_pdo_sqlsrv_7_ts_x86.dll
into my php/ext folder and updated the php.ini. When I open phpinfo I see sqlsrv in both the "Registered PHP Streams" and "PDO drivers" fields.
What should I do to get a successful connection or get more information about why my connection attempt does not succeed/fail?
EDIT:
I've switched to XAMPP (PHP 5.6.24). I am able to connect to the SQL Server via CLI now, but NOT able to connect via PHP-CGI (through the browser/served by Apache HTTPD). I've verified again through php_info() that the sqlsrv and PDO extensions have been successfully loaded. I'm going through the differences between PHP-CGI and PHP CLI now to see what might be causing the issue.
EDIT:
I'm using IIS now instead of Apache and am able to connect via sqlsrv without issues. Not really a solution, but a way around the problem.

try like that :
try {
$db = new PDO( 'sqlsrv:server=serwer_name;Database=database_name', 'user', 'password');
} catch (PDOException $e) {
echo $e->getMessage();
}

Related

How to connect SQL Server through DSN in PHP Apache ? (It's not working when Apache Service is On)

Actually I have try to connect SQL server by using sqlsrv_connect and using the DSN (Data Source Name) without Apache service then the both are perfectly working.
The problem is when I turn on the apache service then php cannot connect to the sql server using odbc DSN (Working with sqlsrcv_connect).
The condition is I need to turn on the apache with a application running using sql server which using DSN. I working with crystal report thats why really need this method. I have tried using system DSN instead user dsn, its also not working.
!
I wrote code below to test my scenario
// Connect to the data source
$conn=odbc_connect('DSNNAME','DBUSER','DBPASS');
if ($conn){
echo "Connection established DSN";
}
else {
echo "Connection using DSN Failed:" . odbc_errormsg();
}
// Connect through server name
$serverName = "WEBSERVER\SQLEXPRESS"; //serverName\instanceName, portNumber (default is 1433)
$connectionInfo = array( "Database"=>"DBNAME", "UID"=>"DBUSER", "PWD"=>"DBPASS");
$conn2 = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn2 ) {
echo "Connection established using server name";
}else{
echo "Connection could not be established by using server name";
die( print_r( sqlsrv_errors(), true));
}
The Result when Apache service is on.
Make sure the ODBC DSN matches the Crystal runtime in terms of 32-bit or 64-bit.

Connecting SQL server DB to A PHP web application using Wamp

I have searched through many posts trying to find an answer but get nowhere.
I am trying to establish a connection to and Sql Server DB through my PHP web application using WAMP.
What I have tried:
I downloaded the sql drivers for PHP 7 and 7.1 and tried them with the corresponding PHP versions
I made sure to restart all services after updating the php.ini file.
I haveinstalled the SQLSRV40.EXE and updated the php.ini with:
extension=php_pdo_sqlsrv_7_ts_x64.dll
extension=php_pdo_sqlsrv_7_nts_x64.dll
I did not though that even though these are added in the php.ini they were not in the php> php extentions list - not sure why
This is my code below allow with the error
<?php
$serverName="DESKTOP-0KNJ0KP";
$connectionInfo=array("Database"=>"SPMS_db",);
$conn=sqlsrv_connect($serverName,$connectionInfo);
if ($conn) {
echo "Connected.<br />";
} else {
echo "Connection failed.<br />";
die( print_r( sqlsrv_errors(), true));
}
?>
I have added context fro PHPinfo()
You have installed PDO_sqlsrv part of PHP Driver for SQL Server, but your code uses sqlsrv functions. You have two options:
install php_sqlsrv_ extensions to make these functions work or
rewrite your code to use PDO version of the driver
PHP code using PDO version of PHP Driver for SQL Server:
<?php
# Connection
$server = "DESKTOP-0KNJ0KP";
$database = "SPMS_db";
try {
$conn = new PDO( "sqlsrv:Server=$server;Database=$database", NULL, NULL);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch( PDOException $e ) {
die( "Error connecting to SQL Server. ".$e->getMessage() );
}
# End
$conn = null;
?>
Connecting through PDO library (which is already installed in your server) is easier.
See PDO Book from PHP.NET: https://www.php.net/manual/en/ref.pdo-dblib.php

Connection error to SQL Server via PHP, SQL STATE IM004, Driver's SQLAllocHandle on SQL_HANDLE_ENV failed

I already have searched and googling about my question, but i still have not find the answer. My problem is when connecting to my SQL Server database via PHP PDO/ODBC Connection, i always getting error : "[Microsoft][ODBC Driver Manager] Driver's SQLAllocHandle on SQL_HANDLE_ENV failed, SQL state IM004 in SQLConnect". But my connection to Oracle or MySQL Database are not problem at all, only to SQL Server database.
Here my code to testing connection :
$dbh = null;
try
{
$dbh = new PDO('oci:dbname='.TNS, DB_USERNAME, DB_PASSWORD, null);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $pe) {
//var_dump($pe->getMessage());
}
if (!is_null($dbh)) {
echo "Oracle Connection success";
}
else {
echo "Oracle cannot connect";
}
echo "<br />";
$dbh = null;
try
{
$dbh = new PDO('mysql:host=localhost;dbname=db_test', 'root', '', null);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $pe) {
//var_dump($pe->getMessage());
}
if (!is_null($dbh)) {
echo "MySQL Connection success";
}
else {
echo "MySQL cannot connect";
}
echo "<br />";
$dbh = null;
try
{
$dbh = new PDO('sqlsrv:server=XXXXX;Database=xxxxxxx', 'xxxx', 'xxxx', null);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $pe) {
//var_dump($pe->getMessage());
}
if (!is_null($dbh)) {
echo "MySQL Connection success";
}
else {
echo "SQL Server cannot connect";
}
The results above is shown as :
Oracle Connection success
MySQL Connection success
SQL Server cannot connect
I have tried to reinstall XAMPP and copying the new PHP's SQL Server library. But the error still same. As i mention above, i have been searching the solution, but still no luck. I truly hope, i can get a solution for my problem, or at least a clue for me to started with. Oh yeah, i almost forgot, this error occurs after Windows 10 update, before that, my connection to SQL Server is fine. So, i wonder whether this problem related to Windows update or not. I really have no clue.
Sorry for my English language, and thank you very much for your helps. I really apreciated for any answer
I was having the same issue and these are the steps I took to make sure it was working correctly:
My Config (Win10, XAMPP, PHP 7.2.8)
1) Downloaded the Microsoft PHP Drivers for SQL Server 5.3 and put the following files in the C:\xampp\php\ext directory:
php_sqlsrv_72_ts_x86.dll
php_pdo_sqlsrv_72_ts_x86.dll
2) Added the following lines to my php.ini file in c:\xampp\php
extension=php_pdo.dll
extension=php_sqlsrv_72_ts_x86.dll
extension=php_pdo_sqlsrv_72_ts_x86.dll
Note: I was originally missing the first line (extension=php_pdo.dll) and that gave me a "Driver's SQLAllocHandle on SQL_HANDLE_ENV failed" error. You do not need to put the dll in the ext directory because in PHP 7 it is built-in but you do need to put the line in the ini file.
3) Downloaded and installed Microsoft ODBC Driver for SQL Server 17.
Make sure you stop and restart the Apache server after making the changes.

Can't establish connection to SQL in windows server 2012

I've found myself in a Job where I have to work with a windows server (2012) - I've never had problems with establishing DB connection, but now I dont seem to find any right solution.
I'll show you my connecting php code:
error_reporting(-1);
ini_set('display_errors', 1);
$DB = array ('dbname'=>"test" , 'user'=> '***' , 'passwort'=> '***', 'host'=>'somelocalnetwork ip 192.**');
$connect = "mysql:dbname=".$DB['dbname']."; host=".$DB['host'];
try
{
$dbh = new PDO($connect,$DB['user'], $DB['passwort']);
echo "Connection established.";
$dbh = null;
}
catch (PDOException $e)
{
echo $e -> getMessage();
}
This is the result, that i get in my browser:
SQLSTATE[HY000] [2002] Es konnte keine Verbindung hergestellt werden, da der Zielcomputer die Verbindung verweigerte.
translated into english :
No connection could be made because the target machine actively refused it .
NOTE:
I downloaded mssql drivers and sqlsrv drivers and extracted them to the /ext/ direcoty , included them in the php ini file.
But when checking the php_info() i dont see any mssql nor sqlsrv parts.
I don't know if thats relevant
The Windows Server is set as WebServer and as normal Microsoft SQL Server
To connect to sql sever using sqlsrv:
<?php
error_reporting(E_ALL);
$serverName = "SuperComputer-PC";
$connectionInfo = array('Database'=>'RiverDatabase', "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect($serverName, $connectionInfo);
if($conn) {
"Connection established.<br />";
}else {
"Connection could not be established.<br />";
die(print_r(sqlsrv_errors(), true));
}
?>
Download php SQL Server from:
http://www.microsoft.com/en-za/download/details.aspx?id=20098
and copy the relevant drivers to your php ext folder.
add the extensions to the php.ini file, for example:
I am using 5.4, but this should work for 5.5, I am not sure if a driver exists for 5.6 yet, but if it does, that's great.
it might be 1) Authorization of pc needed Or
2)port number(lesser chances).
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Or Try
try
{
if ($db = mysqli_connect($hostname_db, $username_db, $password_db))
{
//do something
}
else
{
throw new Exception('Unable to connect');
}
}
catch(Exception $e)
{
echo $e->getMessage();
}
For Connection Problem:
If this happens always, it literally means that the machine exists but that it has no services listening on the specified port, or there is a firewall stopping you.
If it happens occasionally - you used the word "sometimes" - and retrying succeeds, it is likely because the server has a full 'backlog'.
When you are waiting to be accepted on a listening socket, you are placed in a backlog. This backlog is finite and quite short - values of 1, 2 or 3 are not unusual - and so the OS might be unable to queue your request for the 'accept' to consume.
The backlog is a parameter on the listen function - all languages and platforms have basically the same API in this regard, even the C# one. This parameter is often configurable if you control the server, and is likely read from some settings file or the registry. Investigate how to configure your server.
If you wrote the server, you might have heavy processing in the accept of your socket, and this can be better moved to a separate worker-thread so your accept is always ready to receive connections. There are various architecture choices you can explore that mitigate queuing up clients and processing them sequentially.
Regardless of whether you can increase the server backlog, you do need retry logic in your client code to cope with this issue - as even with a long backlog the server might be receiving lots of other requests on that port at that time.
There is a rare possibility where a NAT router would give this error should it's ports for mappings be exhausted. I think we can discard this possibility as too much of a long shot though, since the router has 64K simultaneous connections to the same destination address/port before exhaustion.

Fail to connect to Microsoft sql server

I'm trying to connect a php script to a Microsoft SQL Server, Additionally I'm doing some testing on my own to learn more about php and servers.
if(function_exists("sqlsrv_connect"))
{
echo "exists<br/>";
}else
{
die("does not exist<br/>");
}
$serverName = "myTestServer";
$connectionInfo = array( "Database"=>"test_name", "UID"=>"testUser", "PWD"=>"testPwd");
$conn = sqlsrv_connect($serverName, $connectionInfo);
if($conn)
{
echo "sucessful";
}
else
{
echo "failed ";
}
The output is:
exists
failed
Therefore I can see that the .dll was installed as intended. Am I missing something else? or could this be a problem in the server properties?
Whenever a failure occurs with a SQLSRV PHP function, call sqlsrv_errors to find out the root cause. In your case, it seems you don't have the correct SQL Server ODBC drivers installed on the PHP server. Install the drivers as recommended by your error message, and things should improve.

Categories