Connect database with ODBC in PHP

PHP supports a large number of databases to manage data. ODBC is one of the ways to connect database. PHP offers some functions (odbc_connect, odbc_exec, odbc_fetch_row, etc) that are used to connect ODBC and manages our data. To work with these functions we need to configure a Data Source Name (DSN) that we can create by configuring the ODBC. To learn about ODBC configuration click here.

$conn=odbc_connect(‘ tp_odbc ‘,”,”);
$sql=”SELECT * FROM students”;

The above example creates a connection to a DSN called tp_odbc, The odbc_connect() takes four parameters –

  • Data Source Name (SDN)
  • User name (if given while configuring)
  • Password (if given while configuring)
  • Cursor Type(Optional, not used in the above example)

The odbc_exec() function is used to execute an SQL statement. The odbc_exec() takes two parameter –

  • ODBC Connection Object
  • SQL Statement

Now check a full example to retrieve data from MS Access Database using ODBC connectivity.

if (!$conn)
{exit(“Connection Failed: ” . $conn);}
$sql=”SELECT * FROM students “;
if (!$rs)
{exit(“Error in SQL”);}
echo “<table><tr>”;
echo “<th>Student Name</th>”;
echo “<th>Contact No</th></tr>”;
while (odbc_fetch_row($rs))  {
echo “<tr><td>$ std_name </td>”;
echo “<td>$ contact_no </td></tr>”;
odbc_close($conn);//Close ODBC connection
echo “</table>”;


The odbc_fetch_row() function takes two parameters –

  • the ODBC result identifier
  • an optional row number

The odbc_fetch_row() function is used to return records from the result-set. The odbc_fetch_row() function return true if the ODBC result contain one or more record, otherwise it will return false.

The odbc_result() function is used to read fields from a record. This function takes two parameters –

  • The ODBC result identifier
  • A field number or name.

After retrieve the data from database we will close the ODBC connection. The odbc_close() function is used to close an ODBC connection.

Author Info

  • Fredric Veasey

    Hmm it looks like your website ate my first comment (it was super long) so I guess I’ll just sum it up what I submitted and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog writer but I’m still new to everything. Do you have any points for novice blog writers? I’d really appreciate it.

    • Hi Fredric,
      very nice to here from you, If you like to write here contact us through our mail address “”.

      Good Luck