update page now
PHP 8.5.2 Released!

odbc_connect

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_connectデータソースに接続する

説明

odbc_connect(
    string $dsn,
    ?string $user = null,
    #[\SensitiveParameter] ?string $password = null,
    int $cursor_option = SQL_CUR_USE_DRIVER
): Odbc\Connection|false

他の ODBC 関数を使用するには、 この関数が返す接続 ID が必要となります。 異なる db や異なる権限を使用する限り、 複数の接続を同時にオープンすることができます。

いくつかの ODBC ドライバでは、 複雑なストアド・プロシージャの実行時に次のようなエラーにより失敗する可能性があります。 "Cannot open a cursor on a stored procedure that has anything other than a single select statement in it" SQL_CUR_USE_ODBC を使用することにより、 このようなエラーを回避できる可能性があります。 また、いくつかのドライバは odbc_fetch_row() においてオプションの row_number パラメータをサポートしません。 この場合でも、SQL_CUR_USE_ODBC により解決できる可能性があります。

パラメータ

dsn

接続に使用するデータベースソース名。 あるいは、DSNではない接続文字列を使用することもできます。

user

ユーザー名。 dsnuid が含まれている場合、このパラメータは無視されます。 user を指定せずに接続する場合、null を指定します。

password

パスワード。 dsnpwd が含まれている場合、このパラメータは無視されます。 password を指定せずに接続する場合、null を指定します。

cursor_option

この接続で使用するカーソルの型。 通常はこのパラメータは必要ありませんが、いくつかの ODBC ドライバの問題に対処する際には有用です。

次のような定数がカーソル型として定義されています。

  • SQL_CUR_USE_IF_NEEDED
  • SQL_CUR_USE_ODBC
  • SQL_CUR_USE_DRIVER

戻り値

ODBC 接続を返します。 失敗した場合に false を返します

変更履歴

バージョン 説明
8.4.0 引数 odbc は、Odbc\Connection クラスのインスタンスを期待するようになりました。 これより前のバージョンでは、resource を期待していました。
8.4.0 この関数は Odbc\Connection クラスのインスタンスを返すようになりました。 これより前のバージョンでは、resource を返していました。
8.4.0 user および password が nullable となりました。 また、省略できるようになり、デフォルトでは null となるようになりました。
8.4.0 以前のバージョンでは、password に空文字列を指定した場合、 dsn に対して生成される接続文字列に pwd が含まれていませんでした。 このバージョンからは、空文字列が値に指定された pwd を含んだ状態で生成されるようになりました。 以前の挙動に戻したい場合は、passwordnull を指定してください。
8.4.0 以前のバージョンでは、dsnuid または pwd のいずれかが含まれていると、 user および password の両方が常に無視されていました。 このバージョンからは、dsnuid が含まれている場合にのみ user が無視され、 dsnpwd が含まれている場合にのみ password が無視されるようになりました。

例1 DSN なしの接続

<?php
// Microsoft SQL Server using the SQL Native Client 10.0 ODBC Driver - allows connection to SQL 7, 2000, 2005 and 2008
$connection = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $password);

// Microsoft Access
$connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$mdbFilename", $user, $password);

// Microsoft Excel
$excelFile = realpath('C:/ExcelData.xls');
$excelDir = dirname($excelFile);
$connection = odbc_connect("Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=$excelFile;DefaultDir=$excelDir" , '', '');
?>

参考

  • 持続的な接続の場合: odbc_pconnect() - 持続的なデータベース接続を開く

add a note

User Contributed Notes 3 notes

up
20
fr at freedom2ct dot com
6 years ago
Under Windows odbc_connect (and PDO ODBC) apparently uses the Windows locale to handle input and output from e.g. MS access and MS SQL Server databases.

This causes lots of headaches if one is using other than ASCII characters.

Work-round solutions like utf8_encode and mb_convert both fails.

The solution I fund working is to perform the following changes to Windows

Control Panel > Region > Administrative > Change system locale
>Check '<i>Use Unicode UTF-8 for worldwide language support.</i>'
up
6
nunya at damn dot biz
5 years ago
One additional note regarding odbc_pconnect  and possibly other variations of pconnect:

If the connection encounters an error (bad SQL, incorrect request, etc), that error will return with  be present in odbc_errormsg for every subsequent action on that connection, even if subsequent actions don't cause another error.

For example:

A script connects with odbc_pconnect.
The connection is created on it's first use.
The script calls a query "Select * FROM Table1".
Table1 doesn't exist and odbc_errormsg contains that error.

Later(days, perhaps), a different script is called using the same parameters to odbc_pconnect.
The connection already exists, so it is reused.
The script calls a query "Select * FROM Table0".
The query runs fine, but odbc_errormsg still returns the error about Table1 not existing.

I'm not seeing a way to clear that error using odbc_ functions, so keep your eyes open for this gotcha or use odbc_connect instead.
up
3
lffranco at dco.pemex.com
22 years ago
As always Microsoft is clueless... I've been trying to connect to an Access database on a W2K on the network (not a local file, but mapped on the V: drive), via ODBC.

All I got is this message:
Warning: SQL error: [Microsoft][ODBC Microsoft Access Driver] '(unknown)' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides., SQL state S1009 in SQLConnect in d:\apache\cm\creaart.php on line 13

So... I started looking al around and looks like the ODBC driver has some severe problems:

1. It cannot access a Access database via a mapped drive. And this is for ANY application, name it PHP, Coldfusion, whatever
2. You cannot make a system DSN with a UNC (\\Server\resource), so you must map the drive

Cute isn't it?

So... I quit on ODBC and went via ADO, this is the code that works:

=== CODE ===

$db = '\\\\server\\resource\\db.mdb';
$conn = new COM('ADODB.Connection');
$conn->Open("DRIVER={Driver do Microsoft Access (*.mdb)}; DBQ=$db");

// Driver do Microsoft Access (*.mdb)
// must be the name in your odbc drivers, the one you get
// from the Data Sources (ODBC).
// In this case, I'm in Mexico but the driver name is in portuguese, thanks Microsoft.

$sql = 'SELECT username FROM tblUsuarios';
$res = $conn->Execute($sql);
while (!$res->EOF)
{
    print $res->Fields['username']->Value . "<br>";
    $res->MoveNext();
}

$res->Close(); 
$conn->Close(); 
$res = null; 
$conn = null;

=== /CODE ===
To Top