如何用PHP保存上传的图像在数据库中

时间:2013-06-29 07:01:19

标签: php mysql upload

你好写这段代码上传并保存上传的图片在数据库中但是不行,请帮帮我!!

文件1:
     

      <form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >

                <label>File:  
                <input name="myfile" type="file" size="30" />
                </label>

                <input type="submit" name="submitBtn" class="sbtn" value="Upload" />


                  <iframeid="upload_target"name="upload_target"src="#"style="width:0;height:0;border:0px solid #fff;"></iframe>
                </form>
                </div>

文件2:

<?php




   // Edit upload location here
   $destination_path = getcwd().DIRECTORY_SEPARATOR;
   $target_path="my/";
   $result = 0;
   $name=$_FILES['myfile']['name'];
   $target_path = $target_path . basename( $_FILES['myfile']['name']);

   if(@move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
   list($width, $height, $type, $attr) = getimagesize($target_path);
echo "Image width " .$width;
echo "<BR>";
echo "Image height " .$height;
echo "<BR>";
echo "Image type " .$type;
echo "<BR>";
echo "Attribute " .$attr;


      $result = 1;
   }

  // sleep(1);




$link=mysql_connect('localhost','root','');
if(!$link)
{die('you cannot connect to database...');}
$db=mysql_select_db('final');
if(!$db)die('smile');

if (isset($_FILES['myfile']) && $_FILES['myfile']['size'] > 0) {

// define the posted file into variables 
$name = $_FILES['myfile']['name']; 
$tmp_name = $_FILES['myfile']['tmp_name']; 
$type = $_FILES['myfile']['type']; 
$size = $_FILES['myfile']['size']; 

// if your server has magic quotes turned off, add slashes manually 
//if(!get_magic_quotes_gpc()){ 
//$name = addslashes($name); 
//} 

// open up the file and extract the data/content from it 
$extract = fopen($tmp_name, 'r'); 
$content = fread($extract, filesize($tmp_name)); 
$content = addslashes($content); 
fclose($extract);  

// connect to the database 


// the query that will add this to the database 
$s=mysql_query("SET NAMES 'utf8'");
$sql = "INSERT INTO `final`.`products` (`Productcode`, `Productname`, `Price`,`Descriptionofgood`, `image`) VALUES ('','','','','".$target_path."') WHERE `products`.`Productcode`='1371' ";
$results = mysql_query($sql);
if(!$result)die('not');
}

?>

3 个答案:

答案 0 :(得分:1)

从技术上讲,如果它是一个小项目。 您不应该将图像文件存储在&#34;数据库&#34; ;而只是他们的链接(你甚至可能不需要)。图像或任何媒体文件与您的其他文件(html,css,php)一起存储在服务器上。当然,您需要将它们放在专用文件夹中。 没有存储在数据库上的原因:因为它们仅用于数据检索,更重要的是它们的尺寸较小(确实存在更大的尺寸,我说的是一个需要最少资源的小项目。将媒体文件存储在数据库中只是没有效率。

查看您的代码,我可以告诉您正在尝试将文件存储在您的服务器上。

他们使用了一个非常简单的脚本来上传here。在尝试使用服务器之前,请先尝试使用本地主机。

答案 1 :(得分:1)

if(@move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path))不正确。

应为if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path))

删除@

答案 2 :(得分:1)

我为它创建了三个页面

  1. index.php(uplad image的表格)

  2. upload.php(将图像保存在上传文件夹及其在数据库中的路径)

  3. 3.showimage.php(显示数据库中的图像)

    数据库结构

    id int(4)auto increment - image varchar(100) - image_name varchar(50)

    这是代码:

    <强>的index.php

    <form method="post" action="upload.php" enctype="multipart/form-data">
    
    <label>Choose File to Upload:</label><br />
    
    <input type="hidden" name="id" />
    
    <input type="file" name="uploadimage" /><br />
    
    <input type="submit" value="upload" />
    
    </form>
    

    <强> uplad.php

    <?php
    $target_Folder = "upload/";
    
    $uid = $_POST['id'];
    
    $target_Path = $target_Folder.basename( $_FILES['uploadimage']['name'] );
    
    $savepath = $target_Path.basename( $_FILES['uploadimage']['name'] );
    
        $file_name = $_FILES['uploadimage']['name'];
    
        if(file_exists('upload/'.$file_name))
    {
        echo "That File Already Exisit";
        }
        else
        {
    
            // Database 
        con=mysqli_connect("localhost","user_name","password","database_name"); //Change it if required
    
    //Check Connection
            if(mysqli_connect_errno())
            {
                echo "Failed to connect to database" .     mysqli_connect_errno();
            }
    
            $sql = "INSERT INTO image (id,image, image_name)
                        VALUES     ('','$target_Folder$file_name','$file_name') ";
    
            if (!mysqli_query($con,$sql))
            {
                die('Error: ' . mysqli_error($con));
            }
            echo "1 record added successfully in the database";
            echo '<br />';
            mysqli_close($con);
    
            // Move the file into UPLOAD folder
    
            move_uploaded_file( $_FILES['uploadimage']['tmp_name'],     $target_Path );
    
            echo "File Uploaded <br />";
            echo 'File Successfully Uploaded to:&nbsp;' . $target_Path;
            echo '<br />';  
            echo 'File Name:&nbsp;' . $_FILES['uploadimage']['name'];
            echo'<br />';
            echo 'File Type:&nbsp;' . $_FILES['uploadimage']['type'];
            echo'<br />';
            echo 'File Size:&nbsp;' . $_FILES['uploadimage']['size'];
    
        }
    ?>
    
    <a href="showimage.php">Show Image</a>
    

    <强> showimage.php

    <?php
    
    
    $con=mysqli_connect("localhost","user_name","password","test"); //Change it if required
    
    // Check connection
    if (mysqli_connect_errno())
    {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    
    $result = mysqli_query($con,"SELECT * FROM image " );
    
    
    while($row = mysqli_fetch_array($result))
    {
    echo '<img src="' . $row['image'] . '" width="200" />';
    echo'<br /><br />';  
    }
    
    
    mysqli_close($con);
    
    ?>