将图像插入blob类型表时出现问题。如果我通过phpmyadmin手动插入并打印它,我可以获取图像,但是使用此代码我无法插入到表中。在localhost上它可以工作,但在服务器上没有。你能帮忙吗?我已经搜索了论坛,但无法得到正确答案。 这是代码:
<form action="index.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="image"> <input type="submit" value="upload">
</form>
<?php
$file = $_FILES['image']['tmp_name'];
if(!isset($file))
echo "Please select some image";
else
{
$image_name = mysql_real_escape_string($_FILES['image']['name']);
$image = mysql_real_escape_string(file_get_contents($_FILES['image']['tmp_name']));
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size == FALSE)
{
echo "That's not an image";
}
else
{
if (!$insert = mysql_query("insert into image(id, name, image) values ('','$image_name','$image')"))
{
echo "Problem uploading image";
}
else
{
$res = mysql_query("SELECT * FROM image ");
while ($row = mysql_fetch_assoc($res))
{
echo "<img src=data:image/jpeg;base64," . (base64_encode(($row['Image']))) . " style='width:60px;height:60px;'>";
}
}
}
}
?>
如果我回显$ row [&#39; Image&#39;]结果是这样的:&#34;?PNG IHDR ?? vlH cHRMz%?????? u0?`:?o? &#34;等等。
答案 0 :(得分:0)
你甚至没有使用过image_size,所以不需要定义它,另一方面你没有将文件路径存储到db中。首先定义图像的文件路径然后存储它,否则请参考此Reference site
并更新您的查询
("insert into image(id, name, Image) values (null,'$image_name','$image')")
答案 1 :(得分:0)
我认为您在查询之前没有打开数据库连接
$con = mysql_connect("localhost","mysql_user","mysql_pwd");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$query = "your query";
mysql_query($query,$con);
并使用
header("Content-type: image/jpeg");
在echo
图像之前。
答案 2 :(得分:0)
在PDO中解决
$pdo = new PDO('mysql:dbname=database_name;host=localhost', 'username', 'password',
array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$imageName = mysql_real_escape_string($_FILES["image"]["name"]);
$imageData = file_get_contents($_FILES["image"]["tmp_name"]);
$imageType = mysql_real_escape_string($_FILES["image"]["type"]);
$stmt = $pdo->prepare('INSERT INTO image (name,image) VALUES (:name,:image)');
$stmt->bindParam(':image', $imageData, PDO::PARAM_LOB);
$stmt->bindParam(':name', $imageName);
$stmt->execute(array('name' => $imageName, 'image' => $imageData));
echo "Image Uploaded";
$res = mysql_query("SELECT * FROM image ");
while ($row = mysql_fetch_assoc($res))
{
echo "<img src=data:image/jpeg;base64," . (base64_encode(($row['image']))) . " style='width:60px;height:60px;'>";
}