ODBC Driver for MySQL

Connecting to MySQL with PHP and ODBC Driver



Connecting to MySQL from PHP using ODBC Driver for MySQL

PHP is one of the most popular programming languages for website development. ODBC drivers are connectors that make PHP development database agnostic — your software written in PHP will function with any vendor's database management system. You can use functions like odbc_exec() to prepare and execute SQL statements against any databases like MySQL, SQLite, PostgreSQL, etc.

PHP-based projects usually require a data storage, whether a traditional database or a cloud-based database. You can establish a connection to them using ODBC interface. With our ODBC drivers, you can access various data sources and retrieve tables and fields from a database.

Below is a sample PHP script for accessing MySQL via ODBC. The script connects to MySQL database and fetches all records from a table:

Step 1: Connect to ODBC data source

The odbc_connect() function is used to connect to an ODBC data source. Note that the function takes three mandatory parameters: the data source name, username and password. If your database is not password-protected or doesn't require a username, leave these parameters empty. In the following example, a connection is established using the odbc_connect() function in PHP.

 <?php
    $user = "myusername"; 
    $password = "mypassword";
    $ODBCConnection = odbc_connect("DRIVER={Devart ODBC Driver for MySQL};Server=myserver;Database=mydatabase;Port=myport;String Types=Unicode", $user, $password);

Step 2: Execute an SQL statement

If connection is successful, the odbc_exec() function is used to execute a SELECT statement against the dept table in the autotest database.

	$SQLQuery = "SELECT * FROM autotest.dept";
    $RecordSet = odbc_exec($ODBCConnection, $SQLQuery);

Step 3: Print the result set

The odbc_fetch_row() function is used to return records from the result set. While odbc_fetch_row() returns rows, the odbc_result_set() function prints a set of result in HTML table. After all rows from the result set have been printed, the odbc_close() function closes the connection.

   $result = odbc_result_all($RecordSet, "border=1");
   
   odbc_close($ODBCConnection);
?>  

You can modify this script by specifying general settings for each Devart ODBC driver to use any of them with your PHP projects.

© 2015-2024 Devart. All Rights Reserved. Request Support ODBC Forum Provide Feedback