【发布时间】:2020-07-31 23:53:05
【问题描述】:
数据库异常——yii\db\Exception
Error Info: Array
(
[0] => HY000
[1] => 102
[2] => Incorrect syntax near 'PK'. [102] (severity 15) [INSERT INTO [ORDERS] ([ID], [STATUS], [ZIPFILE], [COLOR], [PRICE]) VALUES (87, 1,'PK]
[3] => -1
[4] => 15
)
↵ 原因:PDO异常 SQLSTATE [HY000]:一般错误:102 'PK' 附近的语法不正确。 [102](严重性 15)[插入 [订单]([ID]、[状态]、[ZIPFILE]、[颜色]、[价格])值(87、1、'PK]
在一个 yii2 应用程序中,我正在尝试使用 file_get_uploads php 函数上传一个 zip 文件,首先将 zip 转换为二进制文件并将其保存到 SQL Server 数据库中的“ZIPFILE”列中,但收到上述错误。
看起来 PK 之后的特殊字符正在截断 ZIPFILE 的值以及 SQL 插入字符串中它之后的任何内容。如果我要使用 PHP addslashes() 函数来转义特殊字符,我可以完成插入,但由于附加的斜杠,zip 文件会损坏。更改编码不是一种选择,因为我使用另一个应用程序从数据库中下载数据,并且该应用程序要求这些值采用此编码。
有没有办法在不损坏 zip 文件的情况下转义特殊字符?
我添加了一些代码以使事情更清晰。
App 使用 Yii2 框架
控制器代码
public function actionCreate()
{
$model = new Orders();
$model->load(Yii::$app->request->post())
//populates ZIPFILE property with binary value of the ASCII encoded ZIPFILE string(pre-populated) compressed to a .zip file and read using file_get_contents in the Zip model
$model->ZIPFILE = (new Zip)->asBinaryString($model->ZIPFILE);
if ($model->save()) {
return $this->redirect(['view', 'id' => $model->ID]);
} else {
return $this->render(
'create', [
'model' => $model,
]);
}
}
在 Zip 模型中
private string $_tempFolder = '/somecache/';
public function asBinaryString($content): ?string
{
$fileName = $this->create($content);
$fileAsBinary = file_get_contents(Yii::$app->basePath . $this->_tempFolder . $fileName);
return $fileAsBinary;
}
public function create($content): ?string
{
$zipName = \microtime();
try {
$zip = new \ZipArchive;
if ($zip->open(Yii::$app->basePath . $this->_tempFolder . $zipName, \ZipArchive::CREATE) === true) {
$zip->addFromString(time().'.RTF', $content);
$zip->close();
} else {
throw new Exception(Yii::t('app', 'Archive could not be created in cache folder.'));
}
} catch (\Throwable $th) {
throw $th;
}
return $zipName ?? null;
}
加载回 $model->ZIPFILE 的字符串看起来像这样“PKa��PM?ٟ�1590409143.RTFu��n�0�_e`���Os�R��j����*�Ƅ �A“�5D��`�@0……”
无法使用数据库中的链接将文件存储到磁盘上,因为这是对需要将数据以 zip 格式存储在数据库中的旧版应用程序的增强。
尝试通过使用 PHP bin2hex() 将二进制 zip 转换为十六进制来接近解决方案,但未成功。十六进制没有特殊字符;因此,$model 保存得很好,只是保存到 SQL 服务器的 zip 文件不能被其他应用程序读取。
这不是一个简单的错字问题,在这里使用准备好的语句已经尝试过,但不起作用。
【问题讨论】:
标签: php sql-server yii2