PHP PDO&更新后大对象(LOB)损坏

时间:2017-03-11 16:43:32

标签: php sql-server pdo

几个月前,我的Ubuntu软件包自动将PHP从7.0.8升级到7.0.13,此时我的用于更新存储在SQL数据库中的照片的脚本开始失败。我通过重新安装7.0.8来解决这个问题。上个月,我再次自动更新到7.0.15,我的脚本再次失败。

我的脚本将jpg图像写入MS-SQL数据库,使用PDO& FreeTDS,以及处理照片的大对象(LOB)。我强调它适用于PHP 7.0.8版。以下是一个隔离我的问题的测试脚本。

<?php

$dsn = 'dblib:dbname=photos;host=gary';
$id = 693925;

$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

try {    
       $photo = file_get_contents("coco.jpg");
       $query = "UPDATE photo_table SET photo = :photo WHERE id = :id";
       $stmt = $dbh->prepare($query);
       $stmt->bindValue(":photo", $photo, PDO::PARAM_LOB);
       $stmt->bindValue(":id", $id, PDO::PARAM_INT);
       $stmt->execute();
    }
}
catch (PDOException $e) {
    echo $e->getMessage();
}

结果是“语法不正确”错误!?

SQLSTATE[HY000]: General error: 
102 Incorrect syntax near '����'.[102] (severity 15) [(null)]

使用最新的PHP版本7.0.15,从数据库读取工作,包括将照片作为大对象读取。将每个其他字段写入数据库都没有问题,只能在我的图像上失败。

尽管在过去几周内进行了搜索,我仍然需要找到其他人报告同样的问题。

我正在接受任何建议,无论是对代码的更改,还是一些允许LOB再次运行的配置设置。

2 个答案:

答案 0 :(得分:0)

我建议您使用 bindParam 而不是 bindValue ,因为 bindParam

  

PDOStatement::bindValue()不同,变量绑定为a   参考,只会在当时进行评估   PDOStatement::execute()被称为。{/ p>

   $photo = file_get_contents("coco.jpg");//change this to below
   $photo = fopen($_FILES['file']['tmp_name'], 'rb');

   $query = "UPDATE photo_table SET photo = :photo WHERE id = :id";
   $stmt = $dbh->prepare($query);

   $stmt->bindValue(":photo", $photo, PDO::PARAM_LOB);//change to this below
   $stmt->bindParam(":photo", $photo, PDO::PARAM_LOB);

   $stmt->bindValue(":id", $id, PDO::PARAM_INT);//change this to below
   $stmt->bindParam(":id", $id, PDO::PARAM_INT);

这只是建议点检查...... http://php.net/manual/en/pdo.lobs.php&amp; http://www.php.net/manual/en/pdostatement.bindparam.php#refsect1-pdostatement.bindparam-description

答案 1 :(得分:0)

我的解决方案/解决方法是在将数据发送到SQL之前将二进制文件从图像转换为十六进制表示。

$photo = bin2hex(file_get_contents("coco.jpg"));

在SQL语句中再次将其转换回来。

$query = 
"UPDATE photo_table SET photo=CONVERT(varbinary(max), :photo, 2) WHERE id = :id";