Microsoft SQL Server et Fonctions Sybase (PDO_DBLIB)

Introduction

Avertissement

Ce module est EXPERIMENTAL. Cela signifie que le comportement de ces fonctions, leurs noms et, concrètement, TOUT ce qui est documenté ici peut changer dans un futur proche, SANS PREAVIS ! Soyez-en conscient, et utilisez ce module à vos risques et périls.

PDO_DBLIB est un pilote qui implémente l'interface de PHP Data Objects (PDO) pour autoriser l'accès de PHP au Microsoft SQL Server et aux bases de données Sybase par la bibliothèque FreeTDS.

Cette extension n'est plus disponible sous Windows avec PHP 5.3 et suivant.

Sous Windows, vous devriez utiliser SqlSrv, un driver alternatif pour MS SQL disponible chez Microsoft : » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx .

Si vous ne pouvez pas utiliser SqlSrv, vous pouvez utiliser le driver PDO_ODBC pour se connecter à un serveur de bases de données Microsoft SQL et Sybase, sachant que le driver natif Windows DB-LIB est ancien, non sécurisé niveau thread et plus supporté par Microsoft.

Sommaire

  • PDO_DBLIB DSN — Connexion au Serveur Microsoft SQL et bases de données Sybase
add a note add a note

User Contributed Notes 12 notes

up
5
xwisdom at gmail dot com
3 years ago
Here's how to call a stored procedure from MS SQL Server:

<?php
$return
= null;
$param1 = 'value1';
$param2 = 'value2';

$ds = $db->prepare('{? = call ?,?}');
$ds->bindParam(1, $return, PDO::PARAM_INT | PDO::PARAM_INPUT_OUTPUT,4);
$ds->bindParam(2, $param1, PDO::PARAM_INT | PDO::PARAM_INPUT_OUTPUT,4);
$ds->bindParam(3, $param2, PDO::PARAM_INT | PDO::PARAM_INPUT_OUTPUT,4);

$ds->execute();
?>
up
1
meltir at meltir dot com
3 years ago
Keep in mind the limitation sql server imposes on clients using the connection methods that dblib uses:
no ntext column values can be transmitted, you will get an insightfull '4004' error when trying.

The full text of the error is:
Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier.

For more info on errors that mssql might throw at you, please see:
http://msdn.microsoft.com/en-us/library/aa937595%28v=SQL.80%29.aspx
up
2
ian at helastel dot com
2 years ago
For people with issues inserting UTF-8 / Unicode data using DBLIB, you can't do this natively - but you can workaround the problem by converting the data first.

e.g. inserting into a nvarchar column with collation Latin1_General_CI_AS

...
$res = $db->prepare($sql);
$res->bindValue(':value', iconv('UTF-8', 'ISO8859-1', $value);
...
up
0
TomF
3 years ago
Note that you must connect with an MS SQL user - FreeTDS does not seem to like active directory linked users.
up
0
dpassey at everettsd dot org
5 years ago
For PDO MSSQL connection issues, ensure that you have the updated version of ntwdblib.dll (currently 8.00.194 as of this post).  Overwrite the existing (old) file or place it in the Windows system32 folder.  The version that ships with PHP 5.2.X does not work.  This is a well known issue apparently, but I had a really hard time finding information on this issue until I was able to lock in a file name.  I hope that this helps someone.
up
0
Bryan
5 years ago
To enable the mssql PDO driver under windows you need to:

1) uncomment the "extension=php_pdo_mssql.dll" line from php.ini
2) copy ntwdblib.dll into the directory where you have installed php
up
0
arnolem at free dot fr
6 years ago
I think that PDO_DBLIB is now stable :
You can download the last source at http://pecl.php.net/package/PDO_DBLIB
up
0
Steve H
8 years ago
To connect to SQL Server 2005 Express on Windows, do it like this:

$pdo = new PDO ('mssql:host=localhost,1433;dbname=[redacted]', '[redacted]', '[redacted]');

localhost
localhost\SQLEXPRESS
localhost\1433
localhost:1433

will not work on Windows.

localhost,1433

does work.

YMMV on other OS's; try each.

Also make sure your TCP/IP Properties -> IP Addresses are correct under SQL Server Configuration Manager.
up
0
support at converters dot ru
8 years ago
If You work with MSSQL Server 7.0/2000/... under Windows and use non latin Encoding then better To use PDO_MSSQL until PDO_ODBC bugs will be fixed (MSSQL ext far more stable and usabe for PHP versions <=5.1.2).
If your MSSQL connection use strings in OEM encoding (cp866 for russian charset)

1. Run Microsoft Server/Client Network Utility on work PC and UNCHECK "DBLibrary options"/"Automatic ANSI to OEM conversion"

2. Restart Web server if needed.
up
0
graham1 dot simpson at hsbcib dot com
9 years ago
There is currently little sybase related PDO docs out there. The ones that I found often mention a spec for a dsn that is invalid. Here's how I am currently connecting to sybase ASE:

1. Compile up freetds http://www.freetds.org on top of open client;
2. Add the PDO and PD_DBLIB modules to php 5 as per the documentation; Note: I'm currently using the PDO-beta and PDO_DBLIB-beta;
3. Check mods installed ok using "pear list" and "php -m";

The documentation often says to use "sybase:" as your DSN, this doesn't work. Use "dblib:" instead. Here's an example:

<?php
 
try {
   
$hostname = "myhost";
   
$port = 10060;
   
$dbname = "tempdb";
   
$username = "dbuser";
   
$pw = "password";
   
$dbh = new PDO ("dblib:host=$hostname:$port;dbname=$dbname","$username","$pw");
  } catch (
PDOException $e) {
    echo
"Failed to get DB handle: " . $e->getMessage() . "\n";
    exit;
  }
 
$stmt = $dbh->prepare("select name from master..sysdatabases where name = db_name()");
 
$stmt->execute();
  while (
$row = $stmt->fetch()) {
   
print_r($row);
  }
  unset(
$dbh); unset($stmt);
?>

Hope this helps.
up
-1
twilson at tridiumtech dot com
5 years ago
Hopefully this will help someone who is having problems connecting to MSSQL. I was having a heck of a time trying to get my dev server to connect to a remote MSSQL 2005 box.

When using PDO like so:
<?php
$mssql
= new PDO('dblib:host=<host>;dbname=<dbname>','<user>','<password>');
?>

I was receiving the message:

Adaptive Server is unavailable or does not exist

And mssql_connect() simply told me "Could not connect to server"

I tried everything, different configuration options for FreeTDS/PHP, different versions, etc. But the answer was one line in php.ini:

mssql.secure_connection = Off

This line, which defaults to Off, needs to be ON if you are using NT authentication:

mssql.secure_connection = On

Here is my build:

FreeTDS-0.82 configured like:
./configure --with-tdsver=8.0 --enable-msdblib --with-gnu-ld

PHP 5.2.11 configured like:
./configure --with-mssql=/usr/local --with-pdo-dblib=/usr/local [other options]

Running on Apache/2.2.13 (Unix / Linux)

Feel free to email me if you need help as I've spent 20+ hours reading and fiddling with this issue, so I'm very familiar with it now.

Peace,
Tom
up
-1
tris+php at tfconsulting dot com dot au
5 years ago
If you are struggling with
'Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier.'
when trying to do 'SELECT *' queries:

Obviously the best way to deal with this is change your unicode fields to the ascii equivalent (ntext > text), but if that is not an option here is an implementation based on the info at http://www.rochester.edu/IT/web/WebHelp/mssql/limitations.html which checks the data types of the fields and casts them as neccesary.

<?php
class mssql {
    private static
$statement=null;

    private static
$typemap=array(
       
'ntext' => 'text',
       
'bigint' => 'real',
       
'decimal' => 'real',
       
'float' => 'real',
       
'numeric' => 'real'
   
);
   
    public static function
all_fields($table) {
        if(
self::$statement==null) {
           
$db=pdodb::instance(); // or however you get your global instance
           
$query="SELECT COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=?";
           
self::$statement=$db->prepare($query);
        }
       
       
self::$statement->execute(array($table));
       
       
$fields=array();
       
$need_cast=false;
        while(
$field=self::$statement->fetch()) {
           
$field_quoted=self::quote_field($field['COLUMN_NAME']);
            if(isset(
self::$typemap[$field['DATA_TYPE']])) {
               
$fields[]='CAST('.$field_quoted.' AS '.self::$typemap[$field['DATA_TYPE']].') AS '.$field_quoted;
               
$need_cast=true;
            } else
$fields[]=$field_quoted;
        }
        return (
$need_cast) ? implode(', ',$fields) : '*';
    }
   
    public static function
quote_field($field) {
       
$pos=strpos($field,' ');
        return (
$pos===false) ? $field : '['.$field.']';
    }
}

$db=pdodb:instance(); // singleton PDO instance
$stmt=$db->prepare('SELECT '.mssql::all_fields('My_Table').' FROM My_Table');
$stmt->execute();
...
?>

Essentially mssql::all_fields($table) returns '*' if it can, otherwise the fields listed with the relevant casts in place e.g. 'NoteIdent, Owner, CAST(Note AS text) AS Note'
To Top