Tuesday, March 22, 2011

PHP Database ODBC or PHP Application Programming Interface | PHP API

ODBC is an Application Programming Interface (API) that allows you to connect to a data source (e.g. 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 an ODBC connection is available.

Here is how to create an ODBC connection to a MS Access Database:

1. Open the Administrative Tools icon in your Control Panel.
2. Double-click on the Data Sources (ODBC) icon inside.
3. Choose the System DSN tab.
4. Click on Add in the System DSN tab.
5. Select the Microsoft Access Driver. Click Finish.
6. In the next screen, click Select to locate the database.
7. Give the database a Data Source Name (DSN).
8. Click OK.

Connecting to an ODBC


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

Example :-

PHP Code:
$conodbc_connect("WorldofHacker" ,"""");$sql_query="SELECT * from USERNAME";$resultodbc_exec($con$sql); 


How to fetch Records ?


Now as we have run the query & executed above, Now its time to fetch the query.
We have a simple command to fetch the query, it is
PHP Code:
odbc_fetch_rows($result

Retrieving Fields from a Record


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

Example
PHP Code:
$computername=odbc_result($result,1); 

The code line below returns the value of a field called "Username" :-
PHP Code:
$computername=odbc_result($result,"Username"); 

How to close ODBC Connection


The odbc_close() function is used to close an ODBC connection.
PHP Code:
odbc_close($con); 

Well, All the above were Basics Lets Complete with 1 good Example :-

PHP Code:
<html>
<
body>

<?
php
$con
=odbc_connect("worldofhacker""" ,"");
if (!
$con)
{
exit (
"connection failer: " .$con);
}
$sql_querySelect from username;$query=odbc_exec($sql_query,$con);
if(!
$query)
{
exit (
"Error in SQL");
}

echo 
"<table><tr>";
echo 
"<th>Username</th>";
echo 
"<th>Contact name</th></tr>";
while (
odbc_fetch_rows($query,$con)
{
$computername=odbc_result($query,$con);$contactname=odbc_resule($query,$con);
echo 
"<tr><td>$conputername"</td>;
echo 
"<td>$contactname</td></tr>";
}
odbc_close($con);
echo 
"</table>";?></body>
</html> 


Now you are done with all Basic Knowledge of PHP Application Programming Interface AKA "API".

No comments:

Post a Comment