php - 为什么将图像上传到数据库时出错?
问题描述
我想使用 PHP 将图像上传到数据库中。尝试上传时出现以下错误:
Error:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
dbname:img
tablename:image
column:img
type:LongBLob.
我之前已经设法连接到数据库并且能够插入除图像内容之外的任何内容。这是我的代码:
<form method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button>Go</button>
</form>
<?php
$C = new mysqli("localhost","root","","img");
if(!$C->error) {
echo "Connected";
} else {
echo $C->error;
}
if(isset($_FILES['file'])) {
$F = file_get_contents($_FILES['file']['tmp_name']);
$Q = "insert into image (img) values('$F')";
$R = $C->query($Q);
if($R == true) {
echo "ok";
} else {
echo $C->error;
}
}
?>
解决方案
You get this error because you're essentially taking the raw contents of the file, and dumping it into the SQL statement without any form of sanitizing, or encoding.
Try: addslashes
Simply using addslashes
would escape any conflicting characters that would cause the SQL query to fail.
$F = file_get_contents($_FILES['file']['tmp_name']);
$data = addslashes($F);
$Q = "insert into image (img) values('$data')";
Try: base64_encode
An alternative may be to use base64_encode
instead.
Note: When using this method, your img
column should be of type TEXT
$F = file_get_contents($_FILES['file']['tmp_name']);
$encoded = base64_encode($F);
$Q = "insert into image (img) values('$encoded')";
When retrieving the value from the database, you'll need to base64_decode
in order to get the raw data back again.
推荐阅读
- string - 颤动中的拆分()
- python - 如何在 Flask 中发送 html 代码作为参数?
- c++ - 为什么 getline() 函数在这里不起作用?
- c# - 发布后如何更改使用红隼运行的 Asp 核心 Web 应用程序的 IP 和端口号?
- angular - Angular - 如何从我的服务组件中的订阅返回布尔值?
- javascript - IPAD 上不显示视频
- r - 防止 Shiny selectInput 在更新反应图时过早评估
- javascript - 如何在 React.JS 中通过 className 使元素消失?
- xml - 根据 XSD 中的其他字段值定义要求字段
- java - Runtime.exec() 是否仅适用于某些命令?