Skip to content

How to connect to Azure SQL Server with PHP

Last updated on January 26, 2019


This article demonstrates how to use PHP to connect to an Azure SQL database.

To connect to an Azure SQL or Any SQL server using PHP, you should install the required drivers based on your operating system. i.e you have to install the ODBC driver, then install the PHP Driver for SQL Server.

In this post, I am not going to cover the installation part but I will share PHP script, which you can use, to connect to your Azure SQL server.

try {    
    $hostname = 'your_host_name.database.windows.net';
    $dbname = 'database_name';
    $username = 'database_user';
    $pwd = 'database_password';

    $pdo = new PDO ("dblib:version=8.0;charset=UTF-8;host={$hostname};dbname={$dbname}", $username, $pwd);
    $query = "SELECT * FROM location";
    $statement = $pdo->prepare($query);
    $statement->execute();
    
    $results = $statement->fetchAll(PDO::FETCH_ASSOC);
    var_dump($results);

} catch (PDOException $e) {
    echo "Failed to get DB handle: " . $e->getMessage() . "\n";
    exit;
}
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments