May 11, 2021 PHP
ODBC is an application programming interface (Application Programming Interface, API) that enables us to connect to a data source, such as an MS Access database.
With an ODBC connection, you can connect to any database on any computer on your network as long as the ODBC connection is available.
This is how to create an ODBC connection to the MS Access database:
Note that this configuration must be done on the computer on which your site is located. If you are running Internet Information Services (IIS) on your computer, the instructions above will take effect, but if your site is on a remote server, you must have physical access to that server, or ask your host provider to establish a DSN for you.
odbc_connect() function is used to connect to the ODBC data source. The function has four parameters: the data source name, the user name, the password, and the optional pointer type.
odbc_exec() function is used to execute SQL statements.
The following example creates a connection to a DSN named northwind without a user name and password. Then create and execute a SQL statement:
odbc_fetch_row() function is used to return records from the result set. If the row can be returned, the function returns true, otherwise false is returned.
The function has two parameters: the ODBC result identifier and the optional line number:
odbc_result () function is used to read fields from records. 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:
The following line of code returns the value of a field named "CompanyName":
odbc_close () function is used to close the ODBC connection.
The following example shows how to create a database connection first, then a result set, and then display the data in an HTML table.
<html>
<body>
<?php
$conn=odbc_connect('northwind','','');
if (!$conn)
{exit("Connection Failed: " . $conn);}
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
if (!$rs)
{exit("Error in 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>
</html>
By the end of this section, PHP's knowledge of mySQL databases is over, and for more information about MySQL, please refer to the "MySQL Tutorial" at this site!