php connect to sql server

Подключение MS SQL к PHP 5.3 и выше

Недавно передо мной встала задача: работать с MS SQL из PHP. Поиск в Google по ключевым словам «php mssql» и подобным дал уйму ссылок с примерно одинаковой инструкцией:
— раскомментировать в php.ini строчку extension=php_mssql.dll;
— перезапустить Апач/Денвер;
— наслаждаться.

Однако выяснилось, что начиная с версии 5.3 в состав дистрибутива PHP это расширение не входит и, более того, не поддерживается. Для работы с MS SQL рекомендуется драйвер SqlSrv от Microsoft. Пошаговой инструкции по работе с ним найти не смог, поэтому после ряда проб и ошибок написал свою, которую и предлагаю вашему вниманию.

Первое, с чем придётся столкнуться — это соответствие версий PHP, MS SQL, SqlSrv и Windows.

SqlSrv доступен двух версий: 2.0 и 3.0. Версия 2.0 работает только c MS SQL 2008, при этом поддерживает PHP версий 5.2 и 5.3; версия 3.0 работает только с MS SQL 2012, а PHP поддерживает версий 5.3 и 5.4. При этом необходимо помнить, что MS SQL 2012 работает только под Windows Vista и выше.
На моей машине стоит Windows XP, поэтому были взяты: MS SQL 2008, PHP 5.3.5 и SqlSrv 2.0.

Сначала нужно установить сам сервер MS SQL; неожиданностей в установке нет, обо всех проблемах установщик сообщает вовремя и даёт возможность исправить. Желательно также установить MS SQL Server Management Studio: средство управления базами данных. Установка похожа на установку сервера.

Установка связки Apache+PHP описывалась много и подробно, так что здесь не будем её касаться.

Если PHP только что установлен, нужно также не забыть раскомментировать строчку

PHP готов к работе. Осталось подготовить MS SQL; дело в том, что после установки у него отключены все клиентские протоколы, кроме «Общая память». Нужно их включить; делается это в приложении SQL Server Configuration Manager, идущая в комплекте с сервером.

Теперь все компоненты настроены, и можно проверять работу всей системы. Для этого подойдёт такой скрипт:

$serverName = «Имя сервера»; // Имя сервера задавалось при установке; его также можно увидеть при запуске Management Studio

Если всё правильно, то на экране будет строчка

И последнее: для работы с базой данных из PHP нужно использовать функции семейства sqlsrv_, а не mssql_.

Источник

How to use PHP to connect to sql server

I want to use PHP to connect to sql server database.

I installed xampp 1.7.0(php 5.2) and SQLSRV20. I’ve added the extensions in php.ini and I get this error:

What does this error message mean and how do I connect to SQL Server?

php connect to sql server. Смотреть фото php connect to sql server. Смотреть картинку php connect to sql server. Картинка про php connect to sql server. Фото php connect to sql server

14 Answers 14

enable mssql in php.ini

php connect to sql server. Смотреть фото php connect to sql server. Смотреть картинку php connect to sql server. Картинка про php connect to sql server. Фото php connect to sql server

php connect to sql server. Смотреть фото php connect to sql server. Смотреть картинку php connect to sql server. Картинка про php connect to sql server. Фото php connect to sql server

php connect to sql server. Смотреть фото php connect to sql server. Смотреть картинку php connect to sql server. Картинка про php connect to sql server. Фото php connect to sql server

if your using sqlsrv_connect you have to download and install MS sql driver for your php. download it here http://www.microsoft.com/en-us/download/details.aspx?id=20098 extract it to your php folder or ext in xampp folder then add this on the end of the line in your php.ini file

im using xampp version 5.5 so its name php_pdo_sqlsrv_55_ts.dll & php_sqlsrv_55_ts.dll

if you are using xampp version 5.5 dll files is not included in the link. hope it helps

php connect to sql server. Смотреть фото php connect to sql server. Смотреть картинку php connect to sql server. Картинка про php connect to sql server. Фото php connect to sql server

Use localhost instead of your IP address.

And also double check your mysql username and password.

php connect to sql server. Смотреть фото php connect to sql server. Смотреть картинку php connect to sql server. Картинка про php connect to sql server. Фото php connect to sql server

for further investigation: print out the mssql error message:

It is also important to specify the port: On MS SQL Server 2000, separate it with a comma:

php connect to sql server. Смотреть фото php connect to sql server. Смотреть картинку php connect to sql server. Картинка про php connect to sql server. Фото php connect to sql server

php connect to sql server. Смотреть фото php connect to sql server. Смотреть картинку php connect to sql server. Картинка про php connect to sql server. Фото php connect to sql server

2)edit php.ini file add below line extension=php_pdo_sqlsrv_55_ts.dll extension=php_sqlsrv_55_ts.dll

MS SQL connect to php

After install you will get some files. Store it in your system temp folder

Add to php.ini file extension=php_sqlsrv_72_ts_x64 (php_sqlsrv_72_ts_x64.dll is your file which your copy in 4th step ) extension=php_pdo_sqlsrv_72_ts_x64 (php_pdo_sqlsrv_72_ts_x64.dll is your file which your copy in 4th step )

$serverName =»DESKTOP-me\MSSQLSERVER01″; (servername\instanceName)

Источник

Как подключиться к Microsoft SQL Server через PHP

php connect to sql server. Смотреть фото php connect to sql server. Смотреть картинку php connect to sql server. Картинка про php connect to sql server. Фото php connect to sql server

Давайте определим, что мы уже имеет установленный пакет SQL Server на каком то VPS или сервере с ОС Windows (Например, заказанного у ihc.ru), либо установленный на вашем локальном компьютере для тестов.

На данный момент там есть четыре версии драйвера 2.0, 3.0, 3.1, 3.2. Далее приведена таблица с совместимостью с PHP :

Так же приведем таблицу поддержки разных версий MS SQL Server :

Microsoft Drivers for PHP for SQL Server VersionSupported PHP Versions

Windows Server 2008 R2 SP1

Windows Server 2008 SP2

Windows Server 2012

Windows Server 2012 R2

Windows Server 2008 R2 SP1

Windows Server 2008 SP2

Windows Server 2003 Service Pack 1

Windows Server 2008 R2

Windows Server 2008

Мы для проверки выбрали драйвер версии 3.2 для сервера 2014 года. После скачивания распакуйте полученные файлы в какую-нибудь временную папку. Получите примерно такой список файлов:

php connect to sql server. Смотреть фото php connect to sql server. Смотреть картинку php connect to sql server. Картинка про php connect to sql server. Фото php connect to sql server

php connect to sql server. Смотреть фото php connect to sql server. Смотреть картинку php connect to sql server. Картинка про php connect to sql server. Фото php connect to sql server

Теперь проверяем соединение с БД при помощи следующего шаблона:

Напоследок так же ссылка на на описание API драйвера.

Источник

mssql_connect

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_connect — Открывает соединение с MS SQL server

Эта функция УДАЛЕНА в PHP 7.0.0.

Есть следующие альтернативы:

Описание

mssql_connect() устанавливает соединение с MS SQL server.

Список параметров

Сервер MS SQL. Может также включать номер порта, например hostname:port (Linux), или hostname,port (Windows).

Возвращаемые значения

Возвращает идентификатор соединения с MS SQL в случае успеха, или FALSE при ошибке.

Список изменений

Microsoft Drivers for PHP for SQL Server VersionSupported Windows Server
ВерсияОписание
5.1.0Добавлен параметр new_link

Примеры

Пример #1 Пример использования mssql_connect()

при использовании нестандартного порта
$server = ‘KALLESPC\SQLEXPRESS’ ;

Смотрите также

User Contributed Notes 40 notes

If someone encounters the interesting problem in which PHP can connect to a MSSQL server from the command line but not when running as an Apache module: SELinux prevents Apache (and therefore all Apache modules) from making remote connections by default.

If you use PHP on Windows with Apache as a web server, you may get problems with authentication to MS SQL Server even when you supply all valid credentials.

Check your php.ini file:
; Use NT authentication when connecting to the server
mssql.secure_connection = On

If you have secure_connection = On, make sure that you provide valid credentials in the properties for Apache service in the System Services box. Then you should not send DB username and password from your script to MSSQL Server.

If you want to use specific credentials from a PHP script, then set mssql.secure_connection = Off in your php.ini

If you are not getting success, please check

and to enable them if they are not on, do

The following method: server\instance
does’nt work on unix systems.

An instance is nothing more than specific port address different than 1433. so just discover the port on mssql server and then try to connect using:

For anyone who have to connect to crappy SQL SERVER with \\computer_name\instance_name and failed to connect. There are couple of thing you need do.

1). There’s no needs to install SQL client software in your app server. This would keep your server clean.
2). run cliconfg.exe setup alias in case you needed
3). last and most important, do NOT use ntwdblib.dll came with PHP 4.4.x. It’s not most current. The version I’m using is: 8.00.194 with 274,489 Bytes. And make sure you put this file in your system32 folder.

For those trying to connect PHP 5.2 to a 2005 Microsoft SQL Server Analysis Services (SSAS) cube and execute MDX queries, you have to establish a link via a trusted connection from the Database Service to SSAS using a stored procedure, then execute the stored procedure via PHP.

Here is an example stored procedure that retrieves records from the Adventure Works sample cube that ships with SSAS.

From SQL Server Query Analyzer, you could test it as:

From PHP, you would execute something like the following:

$resultset = mssql_query(«exec testMDX»,$res_id);

then loop thorugh the result set.

— STORED PROCEDURE BEGIN

— Create a temporary table that will be used to hold the MDX output
create table #temp_table (column1 text null, column2 text null);

— Setup a string to hold the MDX so that the precompiler does not try to validate the syntax
SET @MDX = ‘SELECT [Product].[Category].members ON ROWS,
ON COLUMNS
FROM [Adventure Works] ‘ ;

— Setup a string to insert the MDX results into the temporary table
SET @SQL = ‘Insert into #temp_table SELECT * FROM OpenQuery(linked_olap,»’+@MDX+»’)’;

— Execute the SQL and remote MDX query
EXEC (@SQL) ;

— Select the results from the temporary table to return to the calling program
Select column1, column2 from #temp_table ;

— Drop the temporary table
drop table #temp_table;

— Release the TRUSTED connection
exec sp_droplinkedsrvlogin ‘linked_olap’, NULL ;

— Release the link to the Analysis Server
exec sp_dropserver ‘linked_olap’ ;

Источник

How to connect to SQL Server using PHP (Xampp) and PDO driver in Windows

Hello everybody!
All right?

In this post, I would like to demonstrate how to connect to SQL Server using PHP (Xampp) and PDO driver on Windows. Many people find it difficult to install and configure the drivers due to small technical details that go unnoticed and make it impossible to connect PHP to the SQL Server database.

The first step to getting this connection is download Microsoft® ODBC Driver 13.1 for SQL Server® to your machine and perform driver installation.

The next step is to view the information of your environment. To do this, create a file called phpinfo.php in the root of your PHP web server (default directory is C: \ xampp \ htdocs), with the content below:

After viewing this file in your web browser (http: //localhost/phpinfo.php), you should see a screen like this:
php connect to sql server. Смотреть фото php connect to sql server. Смотреть картинку php connect to sql server. Картинка про php connect to sql server. Фото php connect to sql server

In this screen, we need to identify the following environment variables:

After identifying this information, let’s now download Microsoft Drivers for PHP for SQL Server, according to your version of PHP:

Relationship between driver version and PHP version

Driver VersionPHP versionDriver Download
5.9PHP 7.3+ and PHP 8.0Download
5.8PHP 7.2 to PHP 7.4Download
4.3PHP 7.0 and PHP 7.1Download
4.0PHP 7.0Download
3.2PHP 5.6.4 + or PHP 5.5.16 + or PHP 5.4.32Download
3.1PHP 5.5.16 + or PHP 5.4.32Download
3.0PHP 5.4.32 or PHP 5.3.0Download
2.0PHP 5.3.0 or PHP 5.2.4 or PHP 5.2.13Download

Relationship between driver version and ODBC driver version

Driver VersionODBC Driver or SQL Server Native Client Driver Version
4.3Microsoft ODBC 11 Driver for SQL Server
ou Microsoft ODBC 13.1 Driver for SQL Server
4.0Microsoft ODBC 11 Driver for SQL Server
ou Microsoft ODBC 13 Driver for SQL Server
3.2 or 3.1Microsoft ODBC 11 Driver for SQL Server
3.0SQL Server 2012 Feature Pack
2.0Microsoft SQL Server 2008 R2 Native Client 32 bits (X86)
ou Microsoft SQL Server 2008 R2 Native Client 64 bits (x64)

Relationship between driver version and database version

Driver VersionDatabase Version
4.3SQL Server 2008 R2 and Above
4.0SQL Server 2008 and above
3.1SQL Server 2008 and above
2.0 and 3.0SQL Server 2005 and above

Relationship between driver version and Windows version

Driver VersionOperating System Version
4.3Windows Server 2012
Windows Server 2012 R2
Windows Server 2016
Windows 8
Windows 8.1
Windows 10
Ubuntu 15.10 (64-bit)
Ubuntu 16.04 (64-bit)
Debian 8 (64-bit)
Red Hat Enterprise Linux 7 (64-bit)
Mac OS Sierra (64-bit)
Mac OS El Capitan (64-bit)
4.0Windows Server 2008 SP2
Windows Server 2008 R2 SP1
Windows Server 2012
Windows Server 2012 R2
Windows Vista SP2
Windows 7 SP1
Windows 8
Windows 8.1
Windows 10
Ubuntu 15.04 (64-bit)
Ubuntu 16.04 (64-bit)
Red Hat Enterprise Linux 7 (64-bit)
3.2 and 3.1Windows Server 2008 R2 SP1
Windows Vista SP2
Windows Server 2008 SP2
Windows 7 SP1
Windows Server 2012
Windows Server 2012 R2
Windows 8
Windows 8.1
3.0Windows Server 2008 R2 SP1
Windows Vista SP2
Windows Server 2008 SP2
Windows 7 SP1
2.0Windows Server Service Pack 2003 1
Windows XP Service Pack 3
Windows Vista Service Pack 1 or later
Windows Server 2008
Windows Server 2008 R2
Windows 7

After identifying the correct driver version according to your version of PHP, SQL Server, and Operating System, download the indicated driver and choose a folder to extract the files to during installation.

After that, copy all the files that were installed to the directory. php \ ext on your Xampp installation (default directory is C: \ xampp \ php \ ext)

php connect to sql server. Смотреть фото php connect to sql server. Смотреть картинку php connect to sql server. Картинка про php connect to sql server. Фото php connect to sql server

If you do not know the path of your configuration file (the default path is C: \ xampp \ php \ php.ini), in the phpinfo () screen shown above, you can identify the correct path of your php file. ini looking for Loaded Configuration File

After copying all files, edit the php.ini file from your installation and add the following records:
extension=php_pdo_sqlsrv_71_ts_x86.dll
extension=php_sqlsrv_71_ts_x86.dll

php connect to sql server. Смотреть фото php connect to sql server. Смотреть картинку php connect to sql server. Картинка про php connect to sql server. Фото php connect to sql server

Remembering that the name of the DLL’s varies according to the version of PHP (71, 70, 54, etc.), Thread-safe (TS or NTS) and architecture (X86 or X64) and must ALWAYS be the same as the name of the files you downloaded and copied it to the php \ ext directory.

Once you have edited the php.ini file, simply restart Apache for the changes to take effect, as shown below:

php connect to sql server. Смотреть фото php connect to sql server. Смотреть картинку php connect to sql server. Картинка про php connect to sql server. Фото php connect to sql server

Open the phpinfo.php file (http: //localhost/phpinfo.php) and see if the driver has now been loaded:
php connect to sql server. Смотреть фото php connect to sql server. Смотреть картинку php connect to sql server. Картинка про php connect to sql server. Фото php connect to sql server

If it is the same as print, it means that the driver is installed and ready to use!

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *