簡體   English   中英

PHP PDO將映像加載到MS SQL Server 2012中

[英]PHP PDO load image into MS SQL Server 2012

我正在嘗試使用PDO將圖像上傳到SQL Server中,就像我將圖像上傳到MySQL中一樣,但沒有成功。

我以為它會像在MySQL中一樣簡單,但是Microsoft確保我會受苦。

我收到的錯誤是: SQLSTATE [IMSSP]:發生錯誤,將輸入參數3的字符串轉換為UCS-2:目標多字節代碼頁中不存在Unicode字符的映射。

我創建了這個小的可運行示例(2個文件“ upload.php”和“ test.html”)。 為了使用MySQL,參數應該為$ db ='mysql'

名為“ upload.php”的php文件內容:

<?php

$db = 'mssql'; // $db = 'mysql';

$config = array(
    'mysql' => array(
        'dsn'       => 'mysql:host=localhost;dbname=',
        'user'      => 'root',
        'password'  => ''
    ),

    'mssql' => array(
        'dsn'       => 'sqlsrv:Server=localhost;Database=',
        'user'      => '',
        'password'  => ''
    )
);

try {
    // connect to database
    $pdoTest = new PDO($config[$db]['dsn'].'test', $config[$db]['user'], $config[$db]['password']);
    $pdoTest->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // insert image to table (with additional some info)
    $queryIn = $pdoTest->prepare("
        INSERT INTO     tbl_image (username, type, image)
        VALUES          (:username, :type, :image);
    ");
    $queryIn->bindValue(':username',  $_POST['username']);
    $queryIn->bindValue(':type',      $_FILES['image']['type']);
    $queryIn->bindValue(':image',     file_get_contents($_FILES['image']['tmp_name']));
    $queryIn->execute();

    // retrieve image and type from table
    $queryOut = $pdoTest->prepare("
        SELECT          type, image
        FROM            tbl_image
        WHERE           username = :username
    ");
    $queryOut->bindValue(':username',  $_POST['username']);
    $queryOut->execute();
    $row = $queryOut->fetch(PDO::FETCH_ASSOC);
    if ($row) {
        // send image back to browser
        header('content-type: '.$row['type']);
        echo $row['image'];
    }
}
catch (PDOException $e) {
    echo $e->getMessage();
}

名為“ test.html”的html文件內容:

<!DOCTYPE html>
<html class="no-overflow">
    <head>
        <meta charset="UTF-8">

        <title>Load image to SQL Server 2012</title>
    </head>

    <body>
        <form enctype="multipart/form-data" action="upload.php" method="POST">
            <input type="text" name="username" autofocus="">
            <input type="file" name="image" accept="image/jpeg">
            <input type="submit" name="submit">
        </form>
    </body>
</html>

MySQL的定義:

database name     'test'
table name        'tbl_image'
field #1          'username varchar(255)'
field #2          'type varchar(255)'
field #3          'image blob'

SQL Server 2012定義:

database name     'test'
table name        'tbl_image'
field #1          'username nvarchar(255)'
field #2          'type nvarchar(255)'
field #3          'image varbinary(MAX)'

我還嘗試了一些較舊的SQL Server示例,但均未成功:

$datastring = file_get_contents($_FILES['image']['tmp_name']);
$data       = unpack("H*hex", $datastring);
$image      = '0x'.$data;

任何想法?

嗨,這是mssql的解決方案代碼

<?php

$db = 'mssql';

$config = array(
    'mysql' => array(
        'dsn'       => 'mysql:host=localhost;dbname=',
        'user'      => 'root',
        'password'  => ''
    ),

    'mssql' => array(
        'dsn'       => 'sqlsrv:Server=localhost;Database=',
        'user'      => '',
        'password'  => ''
    )
);

try {
    // connect to database
    $pdoTest = new PDO($config[$db]['dsn'].'test', $config[$db]['user'], $config[$db]['password']);
    $pdoTest->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // insert image to table (with additional some info)
    $queryIn = $pdoTest->prepare("
        INSERT INTO     tbl_image (username, type, image)
        VALUES          (:username, :type, :image);
    ");
    $queryIn->bindParam(':username',  $_POST['username']);
    $queryIn->bindParam(':type',      $_FILES['image']['type']);
    $queryIn->bindParam(':image',     file_get_contents($_FILES['image']['tmp_name']), PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY);
    $queryIn->execute();

    // retrieve image and type from table
    $queryOut = $pdoTest->prepare("
        SELECT          type, image
        FROM            tbl_image
        WHERE           username = :username
    ");
    $queryOut->bindParam(':username',  $_POST['username']);
    $queryOut->execute();
    $queryOut->bindColumn(2, $image, PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY);
    $row = $queryOut->fetch(PDO::FETCH_ASSOC);
    if ($row) {
        // send image back to browser
        header('content-type: '.$row['type']);
        echo $row['image'];
    }
}
catch (PDOException $e) {
    echo $e->getMessage();
}

在實現了教我的工作解決方案之后,我偶然發現了另一個使用PHP的sqlsrv_connect和sqlsrv_query的解決方案。

    $serverName = "<your_server_name>";
    $dbName = "<your_database>";
    $multipleActiveResultSets = "True";

    // Since UID and PWD are not specified in the $connectionInfo array,
    // The connection will be attempted using Windows Authentication.
    $connectionInfo = array( 
        "Database"=> $dbName, 
        "MultipleActiveResultSets"=> $multipleActiveResultSets        
        );

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

    $query = "INSERT INTO <your_table> (image) VALUES (?)";

    $stmt = sqlsrv_query( $conn, $query, [file_get_contents($_FILES['image']['tmp_name']]);

    if( $stmt === false ) {
        die( print_r( sqlsrv_errors(), true));
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM