MySQL database is usually used to store data for PHP application and data are stored using the MySQL configuration and connection.Today I am going to cover a topic which is to connect PHP and MySQL using ODBC connection as from last two-three days I was working on it.
To make ODBC connection with MySQL tables, First of all you need to install MySQL ODBC drivers that is Connector-ODBC and you can get ODBC drivers from http://www.mysql.com/downloads/connector/odbc/. Once MySQL ODBC connection driver installed in your PC, you need to configure it.
To Configure MySQL ODBC connection follow the below steps:
- Go to Contral Panel >> Administrative Tools and then click Data Sources (ODBC)
- To open the ODBC Data Source Administrator
- Choose the System DSN tab
- Click on Add in the System DSN tab
- Select MySQL ODBC 5.1 Driver, then click Finish
- Now need to configure the specific fields Data source Name for the DSN.
- Click OK to save the DSN
Let’s have a look
In above box, enter the name of the data source(database) you want to access and in the Server field, enter the name of the MySQL hostname that you want to access(e.g localhost) then in user and password field enter database username and password.
Also, Read MySQL Connection: Let be Assured and Database BackUp Script
Now you are connected with ODBC and you can write PHP code for odbc connection with MySQL.
The odbc_connect() function is used to connect to an ODBC data source and The odbc_exec() function is used to execute an SQL statement.
1 2 3 | $conn = odbc_connect('data source name','username','password'); |
After connecting with ODBC, The odbc_fetch_row() function is used to return records from the result-set. This function returns true if it is able to return rows, otherwise false
1 2 3 | odbc_fetch_row($resultset) |
Then, To retrieve fields The odbc_result() function is used to read fields from a record.
1 2 3 | $firstname = odbc_result($resultset,"FirstName"); |
Let’s take one Example which show data after ODBC connection:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $conn=odbc_connect('MyDSN','root','mysqlpass'); // First parameter is your DSN name, second is database username and third is database password $sql = "SELECT * FROM users"; $rs = odbc_exec($conn,$sql); while (odbc_fetch_row($rs)) { $firstname = odbc_result($rs,"FirstName"); // second parameter contain a column name $lastname = odbc_result($rs,"LastName"); } odbc_close($conn); ?> |
OUTPUT
1 2 3 4 5 6 | First Name Last Name Bhumi Shah Zinal Shah |
If you have any query or confusion in above article, Do let me know.Have you developed any application using ODBC, share your thoughts in below comments section.