第一种 方法:
在开发PHP程序时我们可以借助多种连接方式访问各类的数据库获取所需的数据。自PHP5以来PDO作为新生事物将所有数据库接口收入囊中,为开发人员提供了方便快捷的数据库读取方式。本文将介绍如何在Linux服务器配置PHP与SQL Server的连接。
PDO的各种库都可以在PECL中找到,例如,MySQL库:PDO_MYSQL、Oracle库:PDO_OCI。
作为SQL Server 的连接库,通过下面命令下载PDO_DBLIB:
wget http://pecl.php.net/get/PDO_DBLIB
下载完成后通过PEAR安装:
/usr/bin/pear install PDO_DBLIB-1.0.tgz
# 安装出错了: ?如何处理呢?
# /usr/local/php/bin/pear install /root/PDO_DBLIB-1.0.tgz
6 source files, building
WARNING: php_bin /usr/local/php/bin/php appears to have a suffix /bin/php, but config variable php_suffix does not match
running: phpize
Cannot find config.m4.
Make sure that you run '/usr/local/php/bin/phpize' in the top level source directory of the module
ERROR: `phpize' failed
如果安装成功的话,/usr/lib64/php/modules(非64位主机应该在/usr/lib/...)目录中会多出pdo_dblib.so库(如下图)。下面需要将pdo_dblib.so库与php结合起来,进入/etc/php.d 并创建名为pdo_dblib.ini 的文件。在其中写入下面代码:
extension=pdo_dblib.so
service httpd restart
通过一段简单的代码测试能否正常连接MSSQL。利用PDO进行不同类型数据库访问时,只需修改PDO()中的连接参数即可其他调用函数相同,这样在开发时不会因数据库不同而调用不同的操作函数。
<?php $db = new PDO("dblib:host=myHost;dbname=myDB","myUserName","myPassword"); $sql = "select count(*) count from testTable"; $res = $db->query($sql); while ($row = $res->fetch()){ print_r($row); } $res = null; $db = null; ?>
第二种 方式:
$ cd /tmp
$ wgetftp://ftp.ibiblio.org/pub/Linux/ALPH...tds-stable.tgz
$ tar zxvf freetds-stable.tgz
$ ./configure --prefix=/usr/local/freetds
$ make
$ su root
Password:
$ make install
$cd ../php-5.2.5
$./configure --prefix=/usr/local/php
--with-apxs2=/usr/local/apache/bin/apxs
.... 其它参数
--with-mssql=/usr/local/freetds
$ make
$ su root
Password:
# make install
# vim /usr/local/freetds/etc/freetds.conf
# A typical Microsoft SQL Server 7.0 configuration
;[MyServer70]
; host = 192.168.0.1
; port = 1433
; tds version = 7.0
<?php
$conn=mssql_connect("MyServer70","sa","password");
mssql_select_db('dbname',$conn);
$msquery="select firstname,lastname from table";
$msresults=mssql_query($msquery);
while ($row=mssql_fetch_array($msresults)) {
echo
"<li>".
$row['titleofcourtesy'] ." ".$row['firstname'] ." ".$row['lastname'] ."</li>n";
}
?>
$cd ../php-5.2.5
$./configure --prefix=/usr/local/php
--with-apxs2=/usr/local/apache/bin/apxs
.... 其它参数
--enable-pdo
--with-pdo-sqlite
--with-pdo-mysql=/usr/local/mysql/bin/mysql_config
--with-mssql=/usr/local/freetds
--with-pdo-dblib=//usr/local/freetds
$ make
$ su root
Password:
# make install
<?php
try {
$hostname='192.168.0.1';//注意,这里和上面不同,要直接用IP地址或主机名
$port=1433;//端口
$dbname="dbname";//库名
$username="sa";//用户
$pw="password";//密码
$dbh= newPDO("dblib:host=$hostname:$port;dbname=$dbname","$username","$pw");
} catch (PDOException $e) {
echo"Failed to get DB handle: ".$e->getMessage() ."n";
exit;
}
echo'connent MSSQL succeed';
$stmt=$dbh->prepare("select firstname,lastname from table");
$stmt->execute();
while ($row=$stmt->fetch()) {
print_r($row);
}
unset($dbh); unset($stmt);
?>