phpsql-serverdockerfreetds

I need a docker image that can get connected to an external MSSQL datatbase with php


I need a docker image that can get connected to an external MSSQL datatbase when executing a PHP script. I have created one, but I could only get connected to the DB through the tsql CLI. I think it uses Freetds. But when I tried to use a php script I had an error saying that the php could not find the PDO library... Can somebody help me find out what I have missed ?

Here is the image I used:

FROM php:7.4-cli

RUN DEBIAN_FRONTEND=noninteractive apt-get update && apt-get install -y \
  unixodbc unixodbc-dev freetds-dev freetds-bin tdsodbc

ADD freetds.conf /etc/freetds/freetds.conf
ADD locales.conf /etc/freetds/locales.conf

CMD ["/bin/bash"]

and the PHP script look like this: <?php

try {
    $conn = new PDO("dblib:host={$sql_host};dbname={$sql_dbnm}", "$sql_user", "$sql_pswd");
    $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch (Exception $e) {
    var_dump($e);
    die(print_r($e->getMessage()));
}

$tsql = "SELECT field FROM table";
$getResults = $conn->prepare($tsql);
$getResults->execute();

$results = $getResults->fetchAll(PDO::FETCH_BOTH);
foreach($results as $row){
    echo "{$row['field']}\n";
}

Thanks


Solution

  • I have found a way. Here is the content of my Dockerfile:

    FROM php:7.3
    
    # Update packages
    RUN apt-get update
    
    # Install PHP and composer dependencies
    RUN apt-get install gnupg -qq git wget curl libmcrypt-dev libjpeg-dev libpng-dev libfreetype6-dev libbz2-dev libzip-dev
    
    # Clear out the local repository of retrieved package files
    RUN apt-get clean
    
    # Install needed extensions
    # Here you can install any other extension that you need during the test and deployment process
    RUN docker-php-ext-install pdo_mysql zip
    
    # adding custom MS repository
    RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
    RUN curl https://packages.microsoft.com/config/debian/10/prod.list > /etc/apt/sources.list.d/mssql-release.list
    # install SQL Server drivers
    RUN apt-get update && ACCEPT_EULA=Y apt-get install -y unixodbc-dev msodbcsql17
    RUN wget http://pecl.php.net/get/sqlsrv-5.9.0.tgz
    RUN pear install sqlsrv-5.9.0.tgz
    RUN docker-php-ext-enable sqlsrv
    
    RUN wget http://pecl.php.net/get/pdo_sqlsrv-5.9.0.tgz
    RUN pear install pdo_sqlsrv-5.9.0.tgz
    RUN docker-php-ext-enable pdo_sqlsrv
    RUN echo "extension= pdo_sqlsrv.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`
    RUN echo "extension= sqlsrv.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`