使用php在数据库中插入图像

时间:2013-06-09 21:57:34

标签: php database image

我的代码有问题,即使用php在数据库中插入图像代码效果很好但是当我将它连接到数据库时,我开始出错。

upload_image.php

<html>
<head>
<title> Uploading Images</title>
</head>
<body>
</br>
</br>
</br>
<form style="text-align:center" action="upload_image.php"  method="post"   enctype="multipart/form-data">

Select Image: <input type="file"    name="image"  >
<input type="submit"    name="upload"  value ="Upload Now">       
</form>
</body>

</html>

<?php

mysql_connect("localhost","name","pssword")or die(mysql_errno());
mysql_select_db("dbName")or die(mysql_errno());

$file=$_FILES['image']['tmp_name'];

if(!isset($file))   

echo "please select an image";   

else 
{
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addcslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);

if($image_size == FALSE)
echo "this is not an image"; 
else
{
if (!$insert = mysql_query("insert into stores values('','$image_name',$image' )"))
echo "problem uploading image";
else 
{
{ 
$last_id = mysql_insert_id();
echo "image uploaded. <p/> your image:<p/><img src=get_image.php?id=$last_id>";
}   
}
}
}
?>

get_image.php

<?php
mysql_connect("localhost","name","pssword")or die(mysql_errno());
mysql_select_db("dbName")or die(mysql_errno());

$id = addslashes($_REQUEST['id']);
$image = mysql_query("select * from stores where id = $id");
$image= mysql_fetch_assoc($image);
$image = $image['image'];
header("Content-type: image/jpeg");
echo $image;
?>

这是错误:

Notice: Undefined index: image in C:\wamp\www\upload_image.php on line 30

1 个答案:

答案 0 :(得分:3)

$file=$_FILES['image']['tmp_name'];

我相信错误是在这里生成的,因为当它没有设置时,image索引是未定义的(kapow!)

您可以尝试这样做:

if ( ! isset($_FILES['image']))
{
    echo 'Please select a file..';
}
else
{
    // your code
}