FAQ: How do I read an image data and save it into a file with SQL Server Driver for PHP?

Question

 I want to read image data from SQL Server with SQL Server Driver for PHP 2.0, and then save it into a file. However, I could not find a way to figure it out.

 

Answer

You can refer to the following code snippets to resolve this issue:

<?php

/* Connect to the local server using Windows Authentication and

specify the AdventureWorks database as the database in use. */

$serverName = "(local)";

$connectionInfo = array( "Database"=>"AdventureWorks");

$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn === false )

{

   echo "Could not connect.\n";

   die( print_r( sqlsrv_errors(), true));

}

 

/* Set up the Transact-SQL query. */

$tsql = "SELECT LargePhoto

     FROM Production.ProductPhoto

     WHERE ProductPhotoID = ?";

 

/* Set the parameter values and put them in an array. */

$productPhotoID = 70;

$params = array( $productPhotoID);

 

/* Execute the query. */

$stmt = sqlsrv_query($conn, $tsql, $params);

if( $stmt === false )

{

   echo "Error in statement execution.</br>";

   die( print_r( sqlsrv_errors(), true));

}

 

/* Retrieve and display the data.

The return data is retrieved as a binary stream. */

if ( sqlsrv_fetch( $stmt ) )

{

  $image = sqlsrv_get_field( $stmt, 0,

           SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_BINARY));

  //header("Content-Type: image/jpg");

  //fpassthru($image);

 

  $handle = fopen("d:\\test\\test11.jpg","a+");

  if(fwrite($handle,$image)===FALSE){

    echo "Cannot write to file.";

  }

  else

    echo "OK";

  fclose($handle);

  

}