11 February 2020

This snippet shows you how to connect to Azure database for you to run some scripts for an example. In this example we use ODBC class not through PDO. You need to download two packages from your repository or if you are using a distribution where they are not in repository you need to get them from some third party. The packages are msodbcsql and php_odbc. Also you need to enable odbc from php.ini file.

Get packages

Get packages called msodbcsql and php_odbc from repositories or if your distribution doesn't have them, from third party.

Configure php.ini

Enable php-odbc from php.ini file, by uncommenting line "extension=odbc".
Source code viewer
  1. extension=odbc
Programming Language: INI

Connect to database.

Source code viewer
  1. 'Driver={ODBC Driver 17 for SQL Server};'.
  2. 'Server=tcp:[YOUR_DOMAIN].database.windows.net,1433;'.
  3. 'Database=[YOUR_DATABASE];'.
  4. 'Encrypt=yes;'.
  5. 'TrustServerCertificate=no;'.
  6. 'Connection Timeout=30;', '[YOUR_USERNAME]', '[YOUR_PASSWORD]');
  7.  
  8. if ($db) {
  9. $stmt = odbc_prepare($db, "SELECT * FROM table WHERE id = ?");
  10. $success = odbc_execute($stmt, ['12345']);
  11. if (!$success) {
  12. }
  13.  
  14. // ...
  15.  
  16. }
  17. else {
  18. die('Error connecting...');
  19. }
  20.  
Programming Language: PHP

"Escape" strings

Using the method above to run queries, you have to escape your strings. If the string as preceeding or appending single quote(') then the function tries to get the cell content from a file. This is a working workaround for that.
Source code viewer
  1. foreach ($fields_values as $key => $val) {
  2. if (strlen($val) > 1 and $val{0} == "'" and $val{strlen($val)-1} == "'") {
  3. $fields_values[$key] .= ' ';
  4. }
  5. }
Programming Language: PHP