Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP Database ODBC

PHP Database ODBC


ODBC is an Application Programming Interface (API) that gives us the ability to connect to a data source (such as a MS Access database).


Create an ODBC Connection

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

Here is how to create an ODBC connection to an MS Access database:

  1. Open in the Control PanelAdministrative Toolsicon.
  2. Double-click the **Data Sources (ODBC)** icon.
  3. ChoiceSystem DSN tab.
  4. Click in the System DSN tabadd.
  5. ChoiceMicrosoft Access Driver. ClickComplete.
  6. On the next screen, clickChoiceto locate the database.
  7. Give the database adata source name (DSN).
  8. ClickOK.

Please note that this configuration must be completed on the computer where your website is located. If Internet Information Services (IIS) is running on your computer, the above instructions will work; but if your website is on a remote server, you must have physical access to that server, or ask your hosting provider to set up the DSN for you.


Connect to ODBC

The odbc_connect() function is used to connect to an ODBC data source. The function takes four parameters: data source name, username, password, and an optional cursor type.

The odbc_exec() function is used to execute an SQL statement.

Example

The example below creates a connection to a DSN named northwind, without username and password. Then it creates and executes an SQL statement:



$conn=odbc_connect('northwind','','');

$sql="SELECT * FROM customers";

$rs=odbc_exec($conn,$sql);


Fetch Records

The odbc_fetch_row() function is used to return a record from the result set. The function returns true if a row can be returned, otherwise it returns false.

The function has two parameters: the ODBC result identifier and an optional row number:



odbc_fetch_row($rs)


Fetch a Field from a Record

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

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



$compname=odbc_result($rs,1);

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



$compname=odbc_result($rs,"CompanyName");


Close an ODBC Connection

The odbc_close() function is used to close an ODBC connection.



odbc_close($conn);


ODBC Example

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









";

echo "Companyname";

echo "Contactname";



while (odbc_fetch_row($rs))

{

    $compname=odbc_result($rs,"CompanyName");

    $conname=odbc_result($rs,"ContactName");

    echo "$compname";

    echo "$conname";

}

odbc_close($conn);

echo "";

?>