(No version information available, might only be in Git)
sqlsrv_connect — Opens a connection to a Microsoft SQL Server database
Description
sqlsrv_connect(string $serverName
, array $connectionInfo
= ?): resource
Parameters
-
serverName
-
The name of the server to which a connection is established. To connect
to a specific instance, follow the server name with a backward slash
and the instance name (e.g. serverNamesqlexpress). -
connectionInfo
-
An associative array that specifies options for connecting to the server.
If values for the UID and PWD keys are not specified, the connection
will be attempted using Windows Authentication. For a complete list of supported
keys, see » SQLSRV Connection Options.
Return Values
A connection resource. If a connection cannot be successfully opened, false
is returned.
Examples
Example #1 Connect using Windows Authentication.
<?php
$serverName = "serverName\sqlexpress"; //serverNameinstanceName
// Since UID and PWD are not specified in the $connectionInfo array,
// The connection will be attempted using Windows Authentication.
$connectionInfo = array( "Database"=>"dbName");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if(
$conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
?>
Example #2 Connect by specifying a user name and password.
<?php
$serverName = "serverName\sqlexpress"; //serverNameinstanceName
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if(
$conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
?>
Example #3 Connect on a specified port.
<?php
$serverName = "serverName\sqlexpress, 1542"; //serverNameinstanceName, portNumber (default is 1433)
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if(
$conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
?>
Notes
By default, the sqlsrv_connect() uses connection pooling to
improve connection performance. To turn off connection pooling (i.e. force a
new connection on each call), set the «ConnectionPooling» option in the
$connectionOptions array to 0 (or false
). For more information, see
» SQLSRV Connection Pooling.
The SQLSRV extension does not have a dedicated function for changing which
database is connected to. The target database is specified in the
$connectionOptions array that is passed to sqlsrv_connect. To change the
database on an open connection, execute the following query «USE dbName»
(e.g. sqlsrv_query($conn, «USE dbName»)).
See Also
- sqlsrv_close() — Closes an open connection and releases resourses associated with the connection
- sqlsrv_errors() — Returns error and warning information about the last SQLSRV operation performed
- sqlsrv_query() — Prepares and executes a query
alvaro at demogracia dot com ¶
6 years ago
You can use the connectionInfo parameter to specify connection encoding, e.g.:
<?php
$connectionInfo = [
'CharacterSet' => 'UTF-8',
];
$conn = sqlsrv_connect($serverName, $connectionInfo);
?>
Beware though that only two options exist:
- SQLSRV_ENC_CHAR (constant) for ANSI, which is the default
- 'UTF-8' (string) for Unicode
mmi at uhb-consulting dot de ¶
4 years ago
to prevent [Microsoft][ODBC Driver 17 for SQL Server]String data, right truncation Errors on Linux
you must add the Connection Parameter 'CharacterSet' => "UTF-8"
Tested with with Driver Version 5.3
manav at drupal.org/u/manav ¶
5 years ago
If anybody wants to use
<?php
//..
sqlsrv_connect();
//..
?> method to Fedora-25 then user have to install PECL php-sqlsrv library to connect ms-sql server remotely in php script.
In my case i found the same issue but after some search i got this solution and implement it.... now it works.
Anonymous ¶
3 years ago
SQL SERVER 2012 conexion in PHP
<?php
$serverName = "SERVER"; //serverNameinstanceName
$connectionInfo = array( "Database"=>"base", "UID"=>"ex", "PWD"=>"******");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
;
if(
$conn ) {
echo "Conexión establecida.<br />";
}else{
echo "Conexión no se pudo establecer.<br />";
die( print_r( sqlsrv_errors(), true));
}$sql = "SELECT name FROM [base].[dbo].[table]";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $sql , $params, $options );$row_count = sqlsrv_num_rows( $stmt );
if (
$row_count === false)
echo "Error al obtener datos.";
else
echo "bien";
//echo $row_count;while( $row = sqlsrv_fetch_array( $stmt) ) {
print json_encode($row);
}sqlsrv_close($conn);
?>
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Closed
stanedav opened this issue
Mar 7, 2017
· 44 comments
Assignees
Comments
Hello,
I have problem with installing sqlsrv. I am using Ubuntu 16,04 and PHP v. 7.0. I went through the installation as you describing without problem, but with your test php file I am getting this error:
Fatal error: Uncaught Error: Call to undefined function sqlsrv_connect() in /var/www/html/web/testsql.php:17 Stack trace: #0 {main} thrown in /var/www/html/web/testsql.php on line 17
The only difference that I found is, that although I am using PHP 7.0 .so files are in 20160303 folder — I changed the lines in php.ini files, but it still doesnt work.
Could you please help me with this problem? Both php.ini are attached.
Thank you
D. Stanek
php_apache.txt
php_cli.txt
@stanedav You’re receiving this error because the extension is not loaded, could you try this command?
echo "extension= sqlsrv.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:s*||"`
I run this command in /etc/php/7.0/apache2:
When I run it under my user account I get error:
bash:
php —ini | grep «Loaded Configuration» | sed -e «s|.:s||»: Permission denied
So I log into root accout by sudo -i command then I get empty output:
root@dee-desktop:~# echo "extension= sqlsrv.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:s*||"`
root@dee-desktop:~#
Let’s try the commands below, to check if sqlsrv is been loaded or not, and where sqlsrv.so resides
php -m
find /usr/lib/php -name sqlsrv.so
dee@dee-desktop:/etc/php/7.0/apache2$ php -m
[PHP Modules]
calendar
Core
ctype
date
dom
exif
fileinfo
filter
ftp
gettext
hash
iconv
json
libxml
mbstring
mcrypt
openssl
pcntl
pcre
PDO
Phar
posix
readline
Reflection
session
shmop
SimpleXML
sockets
SPL
sqlsrv
standard
sysvmsg
sysvsem
sysvshm
tokenizer
wddx
xml
xmlreader
xmlwriter
xsl
Zend OPcache
zlib
[Zend Modules]
Zend OPcache
dee@dee-desktop:/etc/php/7.0/apache2$ find /usr/lib/php -name sqlsrv.so
/usr/lib/php/20160303/sqlsrv.so
Awesome I can see the sqlsrv
in the list of loaded drivers, Could you restart the apache by sudo service apache2 restart
and run the php script again?
Still the same error…
Fatal error: Uncaught Error: Call to undefined function sqlsrv_connect() in /var/www/html/web/testsql.php:17 Stack trace: #0 {main} thrown in /var/www/html/web/testsql.php on line 17
Could you run testsql.php
through command line by running php /var/www/html/web/testsql.php
?
Also can you move the testsql.php to default localhost /var/www/html
, restart apache sudo service apache2 restart
and then add this line to the php script?
<?php
print_r(get_loaded_extensions());
?>
Here is output:
Array ( [0] => Core [1] => date [2] => libxml [3] => openssl [4] => pcre [5] => zlib [6] => filter [7] => hash [8] => Reflection [9] => SPL [10] => session [11] => standard [12] => apache2handler [13] => mysqlnd [14] => PDO [15] => xml [16] => calendar [17] => ctype [18] => curl [19] => dom [20] => mbstring [21] => fileinfo [22] => ftp [23] => gd [24] => gettext [25] => iconv [26] => imap [27] => intl [28] => json [29] => exif [30] => mcrypt [31] => mysqli [32] => pdo_mysql [33] => pdo_pgsql [34] => pdo_sqlite [35] => pgsql [36] => Phar [37] => posix [38] => readline [39] => shmop [40] => SimpleXML [41] => sockets [42] => sqlite3 [43] => sysvmsg [44] => sysvsem [45] => sysvshm [46] => tokenizer [47] => wddx [48] => xmlreader [49] => xmlwriter [50] => xsl [51] => zip [52] => Zend OPcache )
Fatal error: Uncaught Error: Call to undefined function sqlsrv_connect() in /var/www/html/testsql.php:18 Stack trace: #0 {main} thrown in /var/www/html/testsql.php on line 18
no sqlsrv in list…
is this the result of running the script through command line or apache? I am gonna set up a clean VM and go through the steps, meanwhile could you confirm if you have multiple php installed in different locations?
this is output of edited .php file, you will find it in attachment.
testsql.txt
Yes, I have multiple installations, because before I found this GitHub I found many guides how to install sqlsrv and it needed php 5.6… If I list my /etc/php there are three folders: 5.6 7.0 7.1,…
I am wondering, I dont have any data on my server, and I already set up SSH, maybe I can send you credentials via PM?
I have a hunch that apache is using a different php than what we just configured to load the driver, let’s try an experiment, please run:
1. sudo php -i | grep 'Configuration File'
2. php -v
3. Make sure you have restarted apache after the steps above, and then add phpinfo();
function to php script , and then run apache, you’ll get a page with blue background, can you take an snapshot of the header and the first table?
root@dee-desktop:~# php -i | grep "Configuration File"
Configuration File (php.ini) Path => /etc/php/7.1/cli
Loaded Configuration File => /etc/php/7.1/cli/php.ini
root@dee-desktop:~# php -v
PHP 7.1.2-4+deb.sury.org~xenial+1 (cli) (built: Mar 2 2017 10:39:59) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
with Zend OPcache v7.1.2-4+deb.sury.org~xenial+1, Copyright (c) 1999-2017, by Zend Technologies
(pdf with first part of webpage:)
phpinfo().pdf
Cool! that’s the issue, apache is using php 7.0 with extensions in 20151012 folder, but the configured php is 7.1. either you should configure and load sqlsrv to php.ini file for php 7.0 or load php 7.1 module for apache depending on which php version you wanna use. any preferences?
Nice I see the problem! I dont have any preference, both are acceptable for me…. So how can I change it to proper setup? Thanks
I followed instructions, both 7.0 and 7.1 (the only thing that I did more was removing lines from php.ini in 7.0 with extensions and then I added by echo right one)…
Here is terminal output of whole installation…
php7_0.txt
php7_1..txt
Still getting same error…
@stanedav I went through the log you sent and did the exact steps, but I was unable to get apache run php7.0 and commandline use php 7.1, assuming that php 7.1 is what we want to run on apache, let’s clean up php7.0 dependencies that might be installed from php 7.0 installation
- Clean up
sudo su
apt-get purge libapache2-mod-php7.0
apt-get purge apache2
apt-get purge php.7.0
apt autoremove php7.0-fpm
- install PHP 7.1
sudo su
add-apt-repository ppa:ondrej/php
apt-get update
apt-get -y install php7.1 mcrypt php7.1-mcrypt php-mbstring php-pear php7.1-dev
- install apache and PHP 7.1 apache module
sudo apt-get install libapache2-mod-php7.1
sudo apt-get install apache2
- Configure ini
echo "extension=/usr/lib/php/20160303/sqlsrv.so" >> /etc/php/7.1/apache2/php.ini
echo "extension=/usr/lib/php/20160303/sqlsrv.so" >> /etc/php/7.1/cli/php.ini
- restart apache
sudo service apache2 restart
Hello, thank you very much, error is gone now! But.. I am getting this error in testsql.php:
"db", "Uid" => "user", "PWD" => "pass" ); //Establishes the connection $conn = sqlsrv_connect($serverName, $connectionOptions); //Select Query $tsql= "SELECT @@Version as SQL_VERSION"; //Executes the query $getResults= sqlsrv_query($conn, $tsql); //Error handling if ($getResults == FALSE) die(FormatErrors(sqlsrv_errors())); ?>
Results :
"); } sqlsrv_free_stmt($getResults); function FormatErrors( $errors ) { /* Display errors. */ echo "Error information:
"; foreach ( $errors as $error ) { echo "SQLSTATE: ".$error['SQLSTATE']."
"; echo "Code: ".$error['code']."
"; echo "Message: ".$error['message']."
"; } } ?>
Maybe just syntax error?
@stanedav Could you give me these results of php7.0 installed on a clean machine:
The error you are receiving
using command line
php -i | grep "Configuration File"
php -m | grep sqlsrv
- the result of running the
sqlsrv_connect()
on on command line usingphp var/www/html/testsql.php
Apache
- run the script containing
phpinfo()
- the result of localhost/testsql.php
The set up guide needs updating. I managed to get it working on CLI and apache by adding the following lines:
extension=sqlsrv.so
to
/etc/php/7.0/cli/php.ini
and
/etc/php/7.0/apache2/php.ini
@GDIBass thanks!
@stanedav Can you please try your steps on a fresh machine if possible and also answer @Hadis-Fard’s questions?
@meet-bhagdev Yes, that’s how I solved it. I set up a fresh Ubuntu VirtualBox/Vagrant installation and was trying to solve this issue. Adding the extension in the format mentioned fixed it for my installation, and it seems to be working great now. I am actually NOT the OP, but I was having the same issue so I figured I’d post how I fixed it. FWIW I installed every php extension I could find.
Hello guys, at first thank you all for helping and sorry for delayed answer, it was busy week. I tried to run clean machine again — completely reinstalled ubuntu…
First step was running all steps in https://github.com/Microsoft/msphpsql for Ubuntu 16.04 and for PHP7.0…
Copy of all terminal output during installation:
terminal_output_installation.txt
Then, I added lines to both .ini files (in cli folder and in apache2 folder):
extension=sqlsrv.so
display_errors = on
display_startup_errors = on
Both files are here:
php_apache2.ini.txt
php_cli.ini.txt
Then I created in /var/www/html two files, phpinfo.php and testsql.php…
For phpinfo.php:
phpinfo.php.txt
-
I opened it in web browser — page is empty…
-
from command line — php phpinfo.php, output is here:
-
php_phpinfo.txt
For testsql.php:
testsql.php.txt
- in web browser, I am still getting this error:
"db", "Uid" => "user", "PWD" => "pass" ); //Establishes the connection $conn = sqlsrv_connect($serverName, $connectionOptions); //Select Query $tsql= "SELECT @@Version as SQL_VERSION"; //Executes the query $getResults= sqlsrv_query($conn, $tsql); //Error handling if ($getResults == FALSE) die(FormatErrors(sqlsrv_errors())); ?>
Results :
"); } sqlsrv_free_stmt($getResults); function FormatErrors( $errors ) { /* Display errors. */ echo "Error information:
"; foreach ( $errors as $error ) { echo "SQLSTATE: ".$error['SQLSTATE']."
"; echo "Code: ".$error['code']."
"; echo "Message: ".$error['message']."
"; } } ?>
- from command line — php testsql.php output is here:
php_testsql.txt
@Hadis-Fard output of commands that you send me is here:
terminal_1and2.txt
We made slight changes to the Install Instructions. See https://github.com/Microsoft/msphpsql/tree/dev#install-unix
@stanedav, I tried install instructions on a clean Ubuntu 16.04 machine, they seem to be fine.
Looks like you do not properly enable PHP for Apache and Apache displays the source code instead of executing it. Please try the updated Install Instructions.
Note that, you should have php.7.0.load
and php.7.0.conf
files in /etc/apache2/mods-enabled
folder after you complete the installation steps.
So we can actually work off something scriptable & reproducible, here’s what you are saying is the latest installation instructions (apt-transport-https is required for mssql-tools & the rest are other PHP extensions I require for our sites). Assuming this is run as a script by root:
apt-get update && apt-get upgrade -y
apt-get -y install php7.0 mcrypt php7.0-mcrypt php-mbstring php-pear php7.0-dev php7.0-xml re2c gcc g++ git apt-transport-https php7.0-mysql php7.0-curl php7.0-gd php7.0-intl php7.0-xmlrpc php7.0-zip php7.0-soap php7.0-json php7.0-ldap unattended-upgrades unzip clamav
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
sudo apt-get update
sudo ACCEPT_EULA=Y apt-get install -y msodbcsql mssql-tools
sudo apt-get install -y unixodbc-dev
echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile
echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc
source ~/.bashrc
sudo pecl install sqlsrv
sudo pecl install pdo_sqlsrv
apt-get -y install libapache2-mod-php7.0
apt-get -y install apache2
echo "extension=sqlsrv.so" >> /etc/php/7.0/apache2/php.ini
echo "extension=pdo_sqlsrv.so" >> /etc/php/7.0/apache2/php.ini
sudo service apache2 restart
That results in PHP being rendered as text.
I tried enabling the PHP7.0 module for apache by doing
a2enmod php7.0
sudo service apache2 restart
Which fails. Here is the error log for it
root@scw-74e3fc:~# systemctl status apache2.service
● apache2.service - LSB: Apache2 web server
Loaded: loaded (/etc/init.d/apache2; bad; vendor preset: enabled)
Drop-In: /lib/systemd/system/apache2.service.d
└─apache2-systemd.conf
Active: failed (Result: exit-code) since Tue 2017-03-28 19:03:49 UTC; 7s ago
Docs: man:systemd-sysv-generator(8)
Process: 10268 ExecStop=/etc/init.d/apache2 stop (code=exited, status=0/SUCCESS)
Process: 10368 ExecStart=/etc/init.d/apache2 start (code=exited, status=1/FAILURE)
Mar 28 19:03:49 scw-74e3fc apache2[10368]: * The apache2 configtest failed.
Mar 28 19:03:49 scw-74e3fc apache2[10368]: Output of config test was:
Mar 28 19:03:49 scw-74e3fc apache2[10368]: [Tue Mar 28 19:03:49.746893 2017] [:crit] [pid 10377:tid 139958967220096] Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe. You need to recompile PHP.
Mar 28 19:03:49 scw-74e3fc apache2[10368]: AH00013: Pre-configuration failed
Mar 28 19:03:49 scw-74e3fc apache2[10368]: Action 'configtest' failed.
Mar 28 19:03:49 scw-74e3fc apache2[10368]: The Apache error log may have more information.
Mar 28 19:03:49 scw-74e3fc systemd[1]: apache2.service: Control process exited, code=exited status=1
Mar 28 19:03:49 scw-74e3fc systemd[1]: Failed to start LSB: Apache2 web server.
Mar 28 19:03:49 scw-74e3fc systemd[1]: apache2.service: Unit entered failed state.
Mar 28 19:03:49 scw-74e3fc systemd[1]: apache2.service: Failed with result 'exit-code'.
In the below condensed version of the original instructions, however apache is fully aware of php and returns the same error as reported by @stanedav above.
apt-get update && apt-get upgrade -y
apt-get -y install libapache2-mod-php7.0 apache2 php7.0 mcrypt php7.0-mcrypt php-mbstring php-pear php7.0-dev php7.0-xml re2c gcc g++ git apt-transport-https php7.0-mysql php7.0-curl php7.0-gd php7.0-intl php7.0-xmlrpc php7.0-zip php7.0-soap php7.0-json php7.0-ldap unattended-upgrades unzip clamav
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
sudo apt-get update
sudo ACCEPT_EULA=Y apt-get install -y msodbcsql mssql-tools
sudo apt-get install -y unixodbc-dev
echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile
echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc
source ~/.bashrc
sudo pear config-set php_ini `php --ini | grep "Loaded Configuration" | sed -e "s|.*:s*||"` system
sudo pecl install sqlsrv
sudo pecl install pdo_sqlsrv
echo "extension=sqlsrv.so" >> /etc/php/7.0/apache2/php.ini
echo "extension=pdo_sqlsrv.so" >> /etc/php/7.0/apache2/php.ini
sudo service apache2 restart
You aught to get a script like this to work in a reproducible way before changing the ReadMe
@aspark21 Could you try the following commands and let me know if they fix the issue for you?
a2dismod mpm_event
a2enmod mpm_prefork
a2enmod php7.0
service apache2 restart
@aspark21 , the 2 scripts that you have posted are exactly the same, except you are missing the following line in the first one:
sudo pear config-set php_ini php —ini | grep «Loaded Configuration» | sed -e «s|.:s||» system
I am posting the link to the updated instructions again: https://github.com/Microsoft/msphpsql/tree/dev#install-unix. See «Install the Microsoft PHP Drivers for SQL Server» section.
They are different in the order apache2 & libapache2-mod-php7.0 are installed which you highlighted as being material and the way to fix the issue from occuring.
I was about to add that the clue is probably here assuming this isn’t out of date as that isn’t covered in the current steps defined in the Readme
pecl install pdo_sqlsrv
echo -e "; priority=20nextension=pdo_sqlsrv.so" > /etc/php/7.0/mods-available/pdo_sqlsrv.ini
phpenmod pdo_sqlsrv
Tried that didn’t work.
@ulvii I’ve added the changes you’ve made to the instructions in the below script
apt-get update && apt-get upgrade -y
apt-get -y install php7.0 mcrypt php-solr php7.0-mcrypt php-mbstring php-pear php7.0-dev php7.0-xml re2c gcc g++ git apt-transport-https php7.0-mysql php7.0-curl php7.0-gd php7.0-intl php7.0-xmlrpc php7.0-zip php7.0-soap php7.0-json php7.0-ldap unattended-upgrades unzip clamav
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
sudo apt-get update
sudo ACCEPT_EULA=Y apt-get install -y msodbcsql mssql-tools
sudo apt-get install -y unixodbc-dev
echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile
echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc
source ~/.bashrc
sudo pear config-set php_ini `php --ini | grep "Loaded Configuration" | sed -e "s|.*:s*||"` system
sudo pecl install sqlsrv
sudo pecl install pdo_sqlsrv
apt-get install -y libapache2-mod-php7.0 apache2
a2dismod mpm_event
a2enmod mpm_prefork
a2enmod php7.0
echo "extension=sqlsrv.so" >> /etc/php/7.0/apache2/php.ini
echo "extension=pdo_sqlsrv.so" >> /etc/php/7.0/apache2/php.ini
sudo service apache2 restart
cat /var/www/html/sample.php <<"EOF"
<?php
$serverName = "yourServername";
$connectionOptions = array(
"Database" => "yourDatabase",
"Uid" => "yourUsername",
"PWD" => "yourPassword"
);
//Establishes the connection
$conn = sqlsrv_connect($serverName, $connectionOptions);
//Select Query
$tsql= "SELECT @@Version as SQL_VERSION";
//Executes the query
$getResults= sqlsrv_query($conn, $tsql);
//Error handling
if ($getResults == FALSE)
die(FormatErrors(sqlsrv_errors()));
?>
<h1> Results : </h1>
<?php
while ($row = sqlsrv_fetch_array($getResults, SQLSRV_FETCH_ASSOC)) {
echo ($row['SQL_VERSION']);
echo ("<br/>");
}
sqlsrv_free_stmt($getResults);
function FormatErrors( $errors )
{
/* Display errors. */
echo "Error information: <br/>";
foreach ( $errors as $error )
{
echo "SQLSTATE: ".$error['SQLSTATE']."<br/>";
echo "Code: ".$error['code']."<br/>";
echo "Message: ".$error['message']."<br/>";
}
}
?>
EOF
php /var/www/html/sample.php
Still getting the same error
PHP Warning: sqlsrv_query() expects parameter 1 to be resource, boolean given in /var/www/html/test.php on line 13
Error information: <br/>SQLSTATE: IMSSP<br/>Code: -14<br/>Message: An invalid parameter was passed to sqlsrv_query.<br/>
However the problem is your sample app…..
Having now setup a «normal» application on such a server and the app connects to mssql via adodb mssqlnative just fine. Maybe drop the sample app if it’s going to throw unhelpful errors….
Seems we’ve spent a lot of time going around in circles for nothing just because of that pointless sample app…
Hi @aspark21 ,
I am glad you managed to configure Apache.
In the below condensed version of the original instructions, however apache is fully aware of php and returns the same error as reported by @stanedav above.
Note that, Fatal error: Uncaught Error: Call to undefined function sqlsrv_connect()
means the driver is not loaded.
sqlsrv_query() expects parameter 1 to be resource, boolean given
means the driver is loaded, but the connection was not successful and sqlsrv_connect($serverName, $connectionOptions);
returned false
. Check Return Value section here.
I totally agree that, the sample app should not be executed further if the return value of sqlsrv_connect()
is false
.
Please consider adding the following lines after sqlsrv_connect()
to get the error information about why the connection failed. I will add them to the Readme file too.
if( $conn === false ) {
die( FormatErrors( sqlsrv_errors()));
}
Hello guys, pretty rich conversation here, I tried updated readme, then added extension=sqlsrv.so to both ini files and now it works! Thanks for your effort!
Feel free to reopen the issue if you still need help.
thanks guys for sharing, i have same problm… php 5.5
Hi @Hadis-Fard,
I had a similar problem that @stanedav, but, with the follow differences: MacOs Environment and, in my case I have sqlsrv.so loaded. But with the same message: Call to undefined function mssql_connect().
Could you know how can I fix it?
arrrr!
@yitam thanks. Sorry for the stupid question!
/usr/bin/php7.0 -m
para ver los plugins
@wcadena Er, what is the problem? Please consider creating a new issue.
please state where I can get a sqlsrv.so file for php5.6 ubuntu 14.
@mhgill The sqlsrv driver on Linux only works for PHP 7+. I would suggest upgrading PHP — you can find PHP 7 packages for Ubuntu 14 here.
@stanedav I went through the log you sent and did the exact steps, but I was unable to get apache run php7.0 and commandline use php 7.1, assuming that php 7.1 is what we want to run on apache, let’s clean up php7.0 dependencies that might be installed from php 7.0 installation
sudo su apt-get purge libapache2-mod-php7.0 apt-get purge apache2 apt-get purge php.7.0 apt autoremove php7.0-fpm
sudo su add-apt-repository ppa:ondrej/php apt-get update apt-get -y install php7.1 mcrypt php7.1-mcrypt php-mbstring php-pear php7.1-dev
1. install apache and PHP 7.1 apache module
sudo apt-get install libapache2-mod-php7.1 sudo apt-get install apache2
echo "extension=/usr/lib/php/20160303/sqlsrv.so" >> /etc/php/7.1/apache2/php.ini echo "extension=/usr/lib/php/20160303/sqlsrv.so" >> /etc/php/7.1/cli/php.ini
sudo service apache2 restart
Thank a lot. It helped me as well
- Remove From My Forums
-
Question
-
Hi ,
This is Tamilmani Mohan . I am new entry for this forum . I have an question PHP SQLAzure Connection .
1. I want to connect my db by using SqlAzure .
I followed below steps
1. I have downloaded SQLServerDriverForPHP
2. Extract the folder , all the dll files put into my php extension directory .
3. I added the new line in php.ini file
extension=php_sqlsrv_ts.dll4. I created the sample php page in local directory
following codes are i typed .
$serverName = «(local)»;
$connectionInfo = array( «Database»=>»CRLOCAL»);/* Connect using Windows Authentication. */
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false )
{
echo «Could not connect.n»;
die( print_r( sqlsrv_errors(), true));
}
/* Free the statement and connectin resources. */
sqlsrv_free_stmt( $stmt );
sqlsrv_close( $conn );But I am getting Fatal error: Call to undefined function sqlsrv_connect()
Please one tell me how to resolve this
Thanks
Tamilmani Mohan
Answers
-
Hi ,
I configured everything in properly . I don’t get anything in my php info .So tell me the steps .
Thanks
Tamilmani MohanHello,
You first need to ensure that driver is loaded correctly. So do not try anything from PHP (like sqlsrv_connect( $serverName, $connectionInfo);), until you see the «sqlsrv» in «Registered PHP Streams» when you navigate to the info.php (or whereever you make a call to phinfo() function).The steps are fairly easy and are very well explained in the Help file (.chm) that comes with driver installation.
1. Figure out which version of PHP you are using(5.2.x or 5.3.x). The SQL Server Native drivers for SQL Server 2005/2008 are only working with PHP 5.2.4 or newer !!
2. After knowing which version of driver you need, based on version of PHP, just copy that DLL file into the EXT subfolder of your PHP installation. I suppose that woule be c:php5ext
3. Edit your php.ini file. It shall reside either in your c:Windows or in your c:php5 folder (again based on PHP installation). You may check whre this file is loaded from again from the PHP Info function output (phpinfo()), there is a line like this:
Loaded Configuration File C:php5php.ini
4. Once you edit your php.ini to load the appropriate file, restart your web server to make it reload the new php.ini
5. Check again the output from phpinfo()!
Repeat 1 to 4 until you see «sqlsvr» in «Registered PHP Streams» line of phpinfo() output.Your driver is not properly loaded, and you will not see any warnings for this (besides the Fatal Error for «call to undefined function») until you see «sqlsvr» as part of Registered PHP Streams in the output of phpinfo().
Hope this helps.
-
Proposed as answer by
Monday, March 1, 2010 1:54 PM
-
Marked as answer by
Yi-Lun Luo
Thursday, March 4, 2010 9:40 AM
-
Proposed as answer by
За последние 24 часа нас посетил 11551 программист и 1161 робот. Сейчас ищут 372 программиста …
-
- С нами с:
- 21 дек 2019
- Сообщения:
- 17
- Симпатии:
- 0
Здравствуйте ,скажите с чем связана эта ошибка в какую сторону копать решение.
https://pastebin.com/ez1usuia
Понятно только что sqlsrv_connect — открывает соединение с базой данных SQL Server.
А что композеру не нравится, не понятно
PHP Warning: PHP Startup: Unable to load dynamic library ‘stomp’ (tried: /usr/lib/php/20170718/stomp (/usr/lib/php/20170718/stomp: cannot open shared object file: No such file or directory)
-
Команда форума
Модератор- С нами с:
- 15 мар 2007
- Сообщения:
- 9.901
- Симпатии:
- 968
«Вызов неопределенной функции sqlsrv_connect ()» значит что такая функция в вашем случае не определена. Нужно установить соответствующее расширение.
«Unable to load dynamic library ‘stomp'» — не может загрузить расширение, которое указано в конфигурации. Удалить его из конфигурации или установить. -
- С нами с:
- 21 дек 2019
- Сообщения:
- 17
- Симпатии:
- 0
А кака определить эту функцию? sqlsrv_connect ()
-
Artur_hopf
Активный пользователь- С нами с:
- 7 май 2018
- Сообщения:
- 2.266
- Симпатии:
- 405
@zolka mssql вы не настроили для php
— Добавлено —
Вот такие файлы скачать примерно php_sqlsrv_72_nts.dll , php_pdo_sqlsrv_72_nts.dll72
это к версии php 7.2, у вас скорее всего другая версия. Ищите для своей.
https://docs.microsoft.com/ru-ru/sq…-drivers-php-sql-server?view=sql-server-ver15
И привязать их php.ini-
extension=php_pdo_sqlsrv_72_nts
-
extension=php_sqlsrv_72_nts
— Добавлено —
потом чере phpinfo() посмотреть, подключились или нет -
- С нами с:
- 21 дек 2019
- Сообщения:
- 17
- Симпатии:
- 0
@debian:/etc/php/7.2/apache2$ ls
conf.d php.ini
@debian:/etc/php/7.2/cli$ ls
conf.d php.iniТолько в *cli* или в обои php.ini?
-
Команда форума
Модератор- С нами с:
- 15 мар 2007
- Сообщения:
- 9.901
- Симпатии:
- 968
очевидно это зависит от того какими сами вы пользуетесь и в каких из них нужен данный функционал
apache2 это для вебсервера
cli это для командной строки
Skip to content
There are mostly two php.ini changes files located, in my case, for wamp or xampp server.
One is simple change under the php custom folder changes and the other changes one is in the path of C:wampbinapacheApachex.x.xbin folder.
When connecting to SQL database through sqlsrv_connect used this function,
we are referring to simple the php.ini file in the apache folder.
Add the following php latest version (as per your version) to this file:
extension=c:/wamp/bin/php/php5.4.16/ext/php_sqlsrv_53_ts.dll
PHP Config File Check
Use this simple script to check the your php version:
<?php echo phpinfo(); ?>
Step by Step (call to undefined function sqlsrv_connect() xampp)
Step 1
Download SQLSRV32.EXE (Microsoft Drivers for PHP for SQL Server) from: http://www.microsoft.com/en-us/download/details.aspx?id=20098
Step 2
Choose path: C:xamppphpext
Step 3
simple Uncomment or Append extension = php_sqlsrv_56_ts.dll in php.ini
Step 4
Last step to Restart Apache from XAMPP or wamp server Control Panel (Stop/Start)
Load the simple PHP drivers in php.ini file and restart the server.
extension=php_sqlsrv_53_ts.dll extension=php_pdo_sqlsrv_53_ts.dll
SQL Connection Simple way
<?php $serverName = "200.225.289.248, 1433"; //serverNameinstanceName, portNumber (default is 1433) $connectionInfo = array( "Database"=>"pakainfo", "UID"=>"sa", "PWD"=>"[email protected]"); $conn = sqlsrv_connect( $serverName, $connectionInfo); if( $conn ) { // echo "Connection established.<br />"; }else{ echo "<pre>"; echo "Connection could not be established.<br />"; die( print_r( sqlsrv_errors(), true)); echo "</pre>"; } ?>
SQL Query
$query="select * from pakainfo where mst_id=1"; $stmt = sqlsrv_query( $conn, $query ); $data=array(); while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) { $data[]=$row; }
Example
Subscribe On YouTube : Download Source Code
замечания
Драйвер SQLSRV является поддерживаемым Microsoft расширением PHP, которое позволяет вам обращаться к базам данных Microsoft SQL Server и SQL Azure. Это альтернатива для драйверов MSSQL, которые устарели от PHP 5.3 и были удалены с PHP 7.
Расширение SQLSRV можно использовать в следующих операционных системах:
- Windows Vista с пакетом обновления 2 или более поздней версии
- Windows Server 2008 с пакетом обновления 2 или более поздней версии
- Windows Server 2008 R2
- Windows 7
Для расширения SQLSRV требуется, чтобы собственный клиент Microsoft SQL Server 2012 был установлен на том же компьютере, на котором запущен PHP. Если основной клиент Microsoft SQL Server 2012 еще не установлен, щелкните соответствующую ссылку на странице документации «Требования» .
Чтобы загрузить последние версии драйверов SQLSRV, перейдите по ссылке: Загрузить
Полный список системных требований для драйверов SQLSRV можно найти здесь: Системные требования
Те, кто использует SQLSRV 3.1+, должны загрузить драйвер Microsoft ODBC Driver 11 для SQL Server
Пользователи PHP7 могут загрузить последние версии драйверов от GitHub
Драйвер Microsoft® ODBC 13 для SQL Server поддерживает Microsoft SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016 (Preview), платформу Google Analytics, базу данных Azure SQL и хранилище данных Azure SQL.
Создание соединения
$dbServer = "localhost,1234"; //Name of the server/instance, including optional port number (default is 1433)
$dbName = "db001"; //Name of the database
$dbUser = "user"; //Name of the user
$dbPassword = "password"; //DB Password of that user
$connectionInfo = array(
"Database" => $dbName,
"UID" => $dbUser,
"PWD" => $dbPassword
);
$conn = sqlsrv_connect($dbServer, $connectionInfo);
В SQLSRV также есть драйвер PDO. Для подключения с использованием PDO:
$conn = new PDO("sqlsrv:Server=localhost,1234;Database=db001", $dbUser, $dbPassword);
Создание простого запроса
//Create Connection
$conn = sqlsrv_connect($dbServer, $connectionInfo);
$query = "SELECT * FROM [table]";
$stmt = sqlsrv_query($conn, $query);
Примечание: использование квадратных скобок []
заключается в выходе из table
слов, поскольку это зарезервированное слово . Они работают так же, как backticks `
делают в MySQL .
Вызов хранимой процедуры
Чтобы вызвать хранимую процедуру на сервере:
$query = "{call [dbo].[myStoredProcedure](?,?,?)}"; //Parameters '?' includes OUT parameters
$params = array(
array($name, SQLSRV_PARAM_IN),
array($age, SQLSRV_PARAM_IN),
array($count, SQLSRV_PARAM_OUT, SQLSRV_PHPTYPE_INT) //$count must already be initialised
);
$result = sqlsrv_query($conn, $query, $params);
Создание параметризованного запроса
$conn = sqlsrv_connect($dbServer, $connectionInfo);
$query = "SELECT * FROM [users] WHERE [name] = ? AND [password] = ?";
$params = array("joebloggs", "pa55w0rd");
$stmt = sqlsrv_query($conn, $query, $params);
Если вы планируете использовать один и тот же запрос более одного раза, с разными параметрами, то же самое можно достичь с помощью sqlsrv_prepare()
и sqlsrv_execute()
, как показано ниже:
$cart = array(
"apple" => 3,
"banana" => 1,
"chocolate" => 2
);
$query = "INSERT INTO [order_items]([item], [quantity]) VALUES(?,?)";
$params = array(&$item, &$qty); //Variables as parameters must be passed by reference
$stmt = sqlsrv_prepare($conn, $query, $params);
foreach($cart as $item => $qty){
if(sqlsrv_execute($stmt) === FALSE) {
die(print_r(sqlsrv_errors(), true));
}
}
Получение результатов запроса
Существует 3 основных способа получения результатов запроса:
sqlsrv_fetch_array ()
sqlsrv_fetch_array()
извлекает следующую строку в виде массива.
$stmt = sqlsrv_query($conn, $query);
while($row = sqlsrv_fetch_array($stmt)) {
echo $row[0];
$var = $row["name"];
//...
}
sqlsrv_fetch_array()
имеет необязательный второй параметр для извлечения различных типов массивов: SQLSRV_FETCH_ASSOC
, SQLSRV_FETCH_NUMERIC
и SQLSRV_FETCH_BOTH
(по умолчанию) ; каждый возвращает соответственно ассоциативные, числовые или ассоциативные и числовые массивы.
sqlsrv_fetch_object ()
sqlsrv_fetch_object()
извлекает следующую строку в качестве объекта.
$stmt = sqlsrv_query($conn, $query);
while($obj = sqlsrv_fetch_object($stmt)) {
echo $obj->field; // Object property names are the names of the fields from the query
//...
}
sqlsrv_fetch ()
sqlsrv_fetch()
делает следующую строку доступной для чтения.
$stmt = sqlsrv_query($conn, $query);
while(sqlsrv_fetch($stmt) === true) {
$foo = sqlsrv_get_field($stmt, 0); //gets the first field -
}
Получение сообщений об ошибках
Когда запрос идет не так, важно получить сообщение об ошибке, которое возвращается драйвером, чтобы определить причину проблемы. Синтаксис:
sqlsrv_errors([int $errorsOrWarnings]);
Это возвращает массив с:
ключ | Описание |
---|---|
SQLSTATE | Состояние, в котором находится драйвер SQL Server / OBDC. |
код | Код ошибки SQL Server |
сообщение | Описание ошибки |
Обычно используется вышеуказанная функция:
$brokenQuery = "SELECT BadColumnName FROM Table_1";
$stmt = sqlsrv_query($conn, $brokenQuery);
if ($stmt === false) {
if (($errors = sqlsrv_errors()) != null) {
foreach ($errors as $error) {
echo "SQLSTATE: ".$error['SQLSTATE']."<br />";
echo "code: ".$error['code']."<br />";
echo "message: ".$error['message']."<br />";
}
}
}
I’ve been working on this for 8 hours and still cannot get sqlsrv_connect to work. Thank you, Microsoft. My connection strings work for Access DBs and MySQL — but I can’t get this to work.
For servername, I’ve tried:
$serverName = «MYSERVER»;
$serverName = «(MYSERVERMYINSTANCE)»;
$serverName = «‘MYSERVERMYINSTANCE'»;
$serverName = «(MYSERVER)»;
Setup:
PHP Compiler = MSVC9 (Visual C++ 2008)
C:Program Files (x86)PHPv5.3php.ini
extension_dir C:Program Files (x86)PHPv5.3ext
php_sqlsrv_53_nts_vc9.dll in the extension library.
And I’m getting an error from sqlsrv_errors, so it looks like the DLL is working. Pulling my hair out here.
Any ideas?
$serverName = "MYSERVERMYINSTANCE"; $connectionInfo = array("UID" => $uid, "PWD" => $pwd, "Database"=>"$dbname"); $conn = sqlsrv_connect( $serverName, $connectionInfo); if($conn) { echo "Connection established.n"; } else { echo "Connection could not be established.n"; die( print_r( sqlsrv_errors(), true)); } sqlsrv_close( $conn);
Connection could not be established. Array ( [0] => Array ( [0] => 08001 => 08001 [1] => 53 => 53 [2] =>
Named Pipes Provider: Could not open a connection to SQL Server [53]. => [sql Server Native Client 10.0]Named Pipes Provider: Could not open a connection to SQL Server [53]. ) [1] => Array ( [0] => HYT00 => HYT00 [1] => 0 => 0 [2] => [sql Server Native Client 10.0]Login timeout expired => [sql Server Native Client 10.0]Login timeout expired ) [2] => Array ( [0] => 08001 => 08001 [1] => 53 => 53 [2] => [sql Server Native Client 10.0]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. => [sql Server Native Client 10.0]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. ) )