Connect to Dynamics 365 using PHP

You can connect to Dynamics 365 from PHP using Devart ODBC Driver for Dynamics 365.

Enable the ODBC extension

1. In the php.ini file, uncomment the extension=odbc line.

2. Restart your web server to apply the changes.

Define a connection string

An ODBC connection requires a connection string, which can either use a predefined DSN or be specified through connection string parameters (a DSN-less connection).

For information about available parameters, see Connection string parameters.

DSN connection string

You can use a connection string with a predefined DSN.

$connectionString = "DSN=your_dsn";

If you need credentials other than those used in the DSN, specify them in the connection string to override the DSN values.

$connectionString = "DSN=your_dsn;User ID=your_username;Password=your_password";

For information on configuring a DSN on specific operating systems, see instructions for Windows, macOS, or Linux.

DSN-less connection string

You can establish a connection without a DSN by specifying all necessary parameters directly in the connection string.

The following example uses OAuth 2.0 authentication.

$connectionString = "DRIVER=Devart ODBC Driver for Dynamics 365;Authentication=OAuth;Refresh Token=your_refresh_token";

For more information, see DSN-less connections.

Connect to Dynamics 365

The following PHP code demonstrates how to connect to Dynamics 365 and fetch data using the ODBC driver.

<?php
// Define an ODBC connection string
$connectionString = "your_connection_string";

// Establish the ODBC connection
$connection = odbc_connect($connectionString);

// Check if the connection is successful
if ($connection) {
    echo "Connected to Dynamics 365 successfully.\n";

    // Define a SQL query
    $sql = "SELECT accountid, name FROM account";    

    // Execute the query
    $result = odbc_exec($connection, $sql);

    // Check if the query execution was successful
    if ($result) {
        // Fetch and display the results
        echo "Query results:\n";
        while ($row = odbc_fetch_array($result)) {
            // Print each row of the result set
            print_r($row);
        }
    } else {
        echo "Failed to execute query: " . odbc_errormsg($connection) . "\n";
    }

    // Close the connection
    odbc_close($connection);
    echo "Connection closed.\n";
} else {
    echo "Failed to connect: " . odbc_errormsg() . "\n";
}
?>