Latest web development tutorials

PHP database ODBC

ODBC is an application programming interface (Application Programming Interface, API), so that we have the ability to connect to a data source (such as an MS Access database).

Create ODBC connection

Via an ODBC connection, you can connect to your network in any database on any computer, as long as an ODBC connection is available.

This method is to create ODBC MS Access database connection arrives:

  1. Open theAdministrative Tools icon in the Control Panel.
  2. Double-clickData Sources (ODBC) icon.
  3. Select theSystem DSN tab.
  4. Click the System DSN tabadded.
  5. SelectMicrosoft Access Driver.ClickFinish.
  6. In the next screen, clickSelect to locate the database.
  7. Database from adata source name (DSN).
  8. ClickOK.

Please note that this configuration must be completed on the computer where your web site. If your computer is running Internet Information Services (IIS), the above command will take effect, but if your site is located on a remote server, you must have physical access to the server, or ask your hosting provider for you establish DSN.

Connect to ODBC

odbc_connect () function is used to connect to ODBC data sources. This function takes four parameters: the data source name, user name, password, and an optional pointer type.

odbc_exec () function is used to execute SQL statements.


The following example creates a DSN called northwind reach a connection with no user name and password. Then create and execute a SQL statement:

$sql="SELECT * FROM customers";

Retrieve record

odbc_fetch_row () function is used to return records from a centralized results. If you can return to the line, the function returns true, otherwise returns false.

This function takes two parameters: ODBC result identifier and an optional row number:


Retrieved from the record field

odbc_result () function is used to read the fields from the record. This function takes two parameters: ODBC result identifier and a field number or name.

The following line of code returns the value of the first field from the record:


The following line of code returns the value of a field called "CompanyName" of:


Close ODBC Connection

odbc_close () function is used to close the ODBC connection.


ODBC Examples

The following example shows how to first create a database connection, and then create a result set, and then display the data in an HTML table.


if (!$conn)
	exit("连接失败: " . $conn);

$sql="SELECT * FROM customers";

if (!$rs)
	exit("SQL 语句错误");
echo "<table><tr>";
echo "<th>Companyname</th>";
echo "<th>Contactname</th></tr>";

while (odbc_fetch_row($rs))
	echo "<tr><td>$compname</td>";
	echo "<td>$conname</td></tr>";
echo "</table>";