PHP ODBC
ODBC is an Application Programming Interface (API) that enables us to connect to a data source (such as an MS Access database).
Create an ODBC connection
With an ODBC connection, you can connect to any database on any computer in your network, as long as the ODBC connection is available.
This is how to create an ODBC connection to an MS Access database:
Open the Administrative Tools icon in Control Panel.
Double-click the Data Source (ODBC) icon.
Select the System DSN tab.
Click Add in the System DSN tab.
Select Microsoft Access Driver. Click to complete.
In the next interface, click to select to locate the database.
Give the database a data source name (DSN).
Click Confirm.
Please note that this configuration must be completed on the computer where your website is located. If your computer is running Internet Information Services (IIS), the above instructions will work, but if your website is on a remote server, you must have physical access to the server or ask your hosting provider to provide it for you. Create a DSN.
Connect to ODBC
The odbc_connect() function is used to connect to an ODBC data source. This function has four parameters: data source name, user name, password, and optional pointer type.
The odbc_exec() function is used to execute SQL statements.
Example
The following example creates a connection to a DSN named northwind without a username and password. Then create and execute a SQL statement:
$conn=odbc_connect('northwind','',''); $sql="SELECT * FROM customers"; $rs=odbc_exec($conn,$sql);
Retrieve records
odbc_fetch_row() function is used to return records from the result set . The function returns true if rows can be returned, false otherwise.
This function has two parameters: ODBC result identifier and optional row number:
Retrieve fields from records
The odbc_result() function is used to read fields from records. This function takes 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 the ODBC connection
The odbc_close() function is used to close the ODBC connection.
odbc_close($conn);
ODBC Example
The following example shows how to first create a database connection, then create a result set, and then Display data in an HTML table.
<html> <body> <?php $conn=odbc_connect('northwind','',''); if (!$conn) { exit("连接失败: " . $conn); } $sql="SELECT * FROM customers"; $rs=odbc_exec($conn,$sql); if (!$rs) { exit("SQL 语句错误"); } echo "<table><tr>"; echo "<th>Companyname</th>"; echo "<th>Contactname</th></tr>"; while (odbc_fetch_row($rs)) { $compname=odbc_result($rs,"CompanyName"); $conname=odbc_result($rs,"ContactName"); echo "<tr><td>$compname</td>"; echo "<td>$conname</td></tr>"; } odbc_close($conn); echo "</table>"; ?> </body> </htm>