Home Backend Development PHP Tutorial Guide to connecting Microsoft MSSQL (sql server) with php

Guide to connecting Microsoft MSSQL (sql server) with php

May 30, 2018 pm 01:48 PM
mssql php server

When I was studying ezSQL, I saw mssql_connect() and other functions provided by PHP to connect to MSSQL. I thought that PHP, an open source and popular programming language around the world, should be easy to connect to Microsoft's data, but in reality When executing, I found many difficulties

When I was studying ezSQL, I saw mssql_connect() and other functions provided by PHP to connect to MSSQL. I thought that PHP, an open source and popular programming language around the world, would be very useful for connecting to Microsoft. Data should be a no-brainer, but when it comes to actual implementation, we find that there are many difficulties.

The PHP version I downloaded at the beginning was 5.93. After downloading and adding environment variables for a long time, the phpinfo() function finally successfully ran in the browser. Then when I searched for php_mssql.dll all over the world, I discovered that mssql is no longer natively supported in PHP versions 5.3 and above.

Finally found Microsoft Drivers 3.0 for PHP for SQL Server. I thought that Microsoft’s stuff should be able to do it, but I was helpless to find that SQLSRV30.EXE could not run: "SQLSRV30.EXE is not a valid win32 program. ".

After searching the Internet for a long time, I summarized the following feasible methods, but before that you need to:

Configure MICROSOFT SQL SERVER

1 , download and install sql server. There are many versions now, ranging from 2000 to 2008. Find one and download it yourself.

2. Open the tcp/ip connection method so that the database can be accessed remotely. SQL Server Configuration Manager -> Network Configuration -> Protocols -> TCP/IP enabled

3. Open the data management interface and add users and databases.

4. Install php and configure IIS service.

5. Open the php.ini file in the folder where php is located, and add:

mssql.textlimit = 20971520
mssql.textsize = 20971520
Copy after login

After doing this, you can follow There are three methods to connect to the database:

Use the method that comes with php to connect to MSSQL (not applicable to 5.3 and later versions)

Make sure there is php_mssql.dll in the php ext extension library folder. Then in the configuration in PHP.ini, remove the ";" in front of

;extension=php_mssql.dll

.

Then you can test the connection:

//连接MSSQL
$conn=mssql_connect("实例名或者服务器IP","用户名","密码");

//测试连接
if($conn)
{
 echo "连接成功";
}
Copy after login

Microsoft Drivers for SQL Server for PHP

In July 2008, Microsoft released a new driver for php to connect to SQL Server. It improved some shortcomings of php's own MSSQL function and was developed in the form of a php extension plug-in. Through it, you can use php Easily read and write Microsoft databases.

If your server is using IIS, then you must download it from here:

http://php.iis.net/

Because from the above link It is actually a network development platform integrated by Microsoft. It only provides online installation, but it easily integrates PDO plug-ins and PHP. Of course, there are also some other development functions of Microsoft. But if you don’t need it, you don’t need to install it. Those are in visual studio.

But if you are using Apache, you can go here to download this plug-in directly. It is actually an unzipped file, and several DLL files are unzipped. The specific operations are as follows:

1 ) Download the driver package: http://www.microsoft.com/en-us/download/details.aspx?id=20098.

2) Extract the DLL file to the PHP extension_dir directory, if it says SQLSRV30 .EXE is not a valid win32 program. It may be missing some libraries, it may be vc10, or it may not be run with administrator privileges.

extension_dir = “C:\PHP\ext”

3) Reference the corresponding dynamics in the php.ini configuration file Link library file

extension=php_sqlsrv_52_ts_vc6.dll
extension=php_pdo_sqlsrv_52_ts_vc6.dll
extension=php_pdo.dll

52 and 53 represent PHP’s 5.2.x and 5.3 .x version, choose the one that matches your PHP version;
Choosing vc6 or vc9 mainly depends on what web server software you are using. If you are using IIS, choose vc9, if it is Apache, choose vc6 .
As for ts and nts, it depends on whether the PHP version you installed is thread-safe or non-thread-safe. ts is thread-safe and nts is non-thread-safe.

4) Restart Apache
5) Connect to the database

Test connection code:

<?php
//本地测试的服务名
"(local)";
//使用sql server身份验证,参数使用数组的形式,一次是用户名,密码,数据库名
//如果你使用的是windows身份验证,那么可以去掉用户名和密码
$connectionInfo = array( "UID"=>"root",
    "PWD"=>"root2010",
    "Database"=>"master");

$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));
}
 ?>
Copy after login

at Using FreeTDS under windows

What is FreeTDS? FreeTDS is actually an open source (or can be said to be free) C library, which can access and operate Microsoft's SQL database under the Linux system. It can be used in Sybase's db-lib or ct-lib library, which also contains an ODBC library. Allows many applications to connect to Sybase or Microsoft SQL servers. FreeTDS is released as source code, and because of this, it can be compiled and installed on almost any system.

If your server is a Windows system, then you should use php_dblib.dll. (more information on Using FreeTDS for Unix.)

通常我们可以在这个网站上找到这些DLL文件- Frank Kromann's site, 但是它基本上很多都已经过时了,并且会引发很多的问题,因此我们推荐windows下使用PHP 5.2.x版本,并且看看下面的建议 :

1. 按照下面的表格来下载 php_dblib.dll 并且将其保存到 /PHP/ext 文件夹下面.





PHP versionThread SafeFreeTDS versionDownload URL
PHP 5.2.x (vc6)Yes0.82 + 20090302 patchesDownload!
No0.82 + 20090302 patchesDownload!
PHP 5.3.x (vc9)Yes0.82 + 20090904 patchesDownload!
No0.82 + 20090904 patchesDownload!
PHP 5.4.x (vc9)Yes0.82 + 20110906 patchesDownload! FTP Download!
No0.82 + 20110906 patchesDownload! FTP Download!


2、 FreeTDS 需要安装 .NET Framework v1.1 ,你可以到微软的网站去下载。或者你去Frank's site 下载需要的DLL文件,并保存到你的/PHP根目录下面。

3、在php配置文件 /PHP/php.ini 中添加:

extension=php_dblib.dll

4、当php引擎启动FreeTDS模块的时候需要传递一些信息,使得FreeTDS能够连接到它的默认的数据库。因此它的需要在freetds.conf中定义数据库连接的基本信息,该文件在其根目录下,可以按照你的情况来进行修改:

[global]
host = xxx.xxx.xxx.xxx (host name or ip of the MSSQL server)
port = 1433
client charset = UTF-8
tds version = 8.0
text size = 20971520
5、创建config.php文档来定义数据库连接参数:

$CFG->dbtype = &#39;mssql&#39;; // Required
$CFG->dbhost = &#39;localhost&#39;; // assuming MS SQL is on the same server, otherwise use an IP
$CFG->dbname = &#39;moodle&#39;;  // or whatever you called the database you created
$CFG->dbuser = &#39;yourusername&#39;; // I usually use the &#39;sa&#39; account (dbowner perms are enough)
$CFG->dbpass = &#39;yourpassword&#39;;
$CFG->dbpersist = false;
$CFG->prefix = &#39;mdl_&#39;;  //Prefix, you can change it, but NEVER leave it blank.
Copy after login

6、 重启你的网站,如果还是没有连接到你的数据库的话,在 /PHP/php.ini文件中将display_startup_errors改为"On",当你解决了这些问题之后再将错误报告改为“Off”;
7、测试你的网站,建立test.php文件,代码如下,访问http://localhost/test.php进行测试

<?php
	$link = mssql_connect(&#39;localhost&#39;, &#39;db_user&#39;, &#39;db_password&#39;);
	if(!$link) {
		echo&#39;Could not connect&#39;;
		die(&#39;Could not connect: &#39; . mssql_error());
	}
	echo&#39;Successful connection&#39;;
	mssql_close($link);
?>
Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助。


相关推荐:

php中常量、静态属性、非静态属性的区别

php中静态属性和静态方法区别

php中类和对象:静态属性、静态方法图文详解

The above is the detailed content of Guide to connecting Microsoft MSSQL (sql server) with php. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles