Home > database >  Store image to SQL Server using PHP
Store image to SQL Server using PHP

Time:06-01

I'm trying to save an image into SQL Server database using PHP

CREATE TABLE [dbo].[ImageList](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Image] [varbinary](max) NULL,
[FactID] [varchar](50) NULL,

and my code is:

$img_data = (file_get_contents($_FILES['glryimage']['tmp_name']));
$tsql = "INSERT INTO dbo.ImageList (
            FactID,
            Image) 
            VALUES
            (?, ?)";
$var = array($FactID, $img_data);

if (!sqlsrv_query($conn, $tsql, $var)) {
    if( ($errors = sqlsrv_errors() ) != null) {
        foreach( $errors as $error ) {
            echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
            echo "message: ".$error[ 'message']."<br />";
        }
    }
} else {
}

and when try to insert to database get error

SQLSTATE: IMSSP
message: An error occurred translating string for input param 4 to UCS-2: No mapping for the Unicode character exists in the target multi-byte code page.

Please how I can store an image.

Thanks in advance.

CodePudding user response:

this may be caused due to UTF-8 and UTF-16 character encoding that may not be supported by the server bin2hex PHP function may solve the issue, just give it a try

$img_data = bin2hex(file_get_contents($_FILES['glryimage']['tmp_name']));

use PHP documentation for reference.

bin to hex

hex to bin

  • Related