我在用 php 将照片 (blob) 插入数据库时遇到了一个大问题。我无法执行查询。它返回错误。这是我的代码
public function addPhoto()
{
$ret = false;
$img_blob = '';
$img_titre ='';
$description = "hhhhh";
$selogon = '';
$ret= is_uploaded_file($_FILES['fic']['tmp_name']);
if (!$ret) {
echo "Problème de transfert";
return false;
} else {
$img_titre = $_FILES['fic']['name'];
$img_blob = file_get_contents ($_FILES['fic']['tmp_name']);
$conn = connection();
$sql = "INSERT INTO image (titre,selogon,description,img_blob)
VALUES ( '$img_titre','$selogon','$description','".addslashes ($img_blob)."')" ;
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
}
else {
echo "string";
}
$conn->close();
}
最佳答案
PDO 解决方案
假设你正在使用 PDO(不是你指定的),如果你想将它保存为 blob 那么应该完成以下步骤
try
{
$fp = fopen($_FILES['fic']['tmp_name'], 'rb'); // read the file as binary
$stmt = $conn->prepare("INSERT INTO image (titre, selogon, description, img_blob) VALUES (?, ?, ?, ?)"); // prepare statement
// bind params
$stmt->bindParam(1, $img_titre);
$stmt->bindParam(2, $selogon);
$stmt->bindParam(3, $description);
// this is important I will explain it below after the code
$stmt->bindParam(4, $fp, PDO::PARAM_LOB);
$stmt->execute();
// if you want to check if it was inserted use affected rows from PDO
}
catch(PDOException $e)
{
'Error : ' .$e->getMessage();
}
最重要的是将文件指针($fp)绑定(bind)到称为 LOB 的 PDO 参数,它代表大对象
PDO::PARAM_LOB tells PDO to map the data as a stream, so that you can manipulate it using the PHP Streams API.
http://php.net/manual/en/pdo.lobs.php
之后,您可以使用 PHP 流的强大功能并将其保存为二进制安全流。从流中读取更有意义,但如果我是你,我真的认为如果你想直接在数据库中保存图片,这似乎不是一个好主意。
MYSQLI解决方案:
如果您不使用 PDO,但例如 mysqli,那么流也是个好主意,但解决方案不同。
最好的选择是检查 SHOW VARIABLES LIKE 'max_allowed_packet';
这将打印最大允许的包大小,如果您的图像更大,blob 将被损坏。
要使其正常工作,您需要使用 fread() + loop + feof() 和 mysqli 函数 send_long_data 以较小的 block 发送数据
Example from php.net site:你可以像我上面做的那样根据你的需要进行调整,不同之处在于参数以不同的方式绑定(bind)。
$stmt = $mysqli->prepare("INSERT INTO messages (message) VALUES (?)");
$null = NULL;
$stmt->bind_param("b", $null);
$fp = fopen($_FILES['fic']['tmp_name'], "r");
while (!feof($fp)) {
$stmt->send_long_data(0, fread($fp, 8192));
}
fclose($fp);
$stmt->execute();
关于php - 我无法在数据库中插入照片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49161789/