将图像上传到db在php中出错了

时间:2013-04-27 06:17:47

标签: php database

  1. 一切顺利,但得到了这个错误 Notice: Undefined index: image in C:\wamp\www\neos-final\update-image.php on line 21
  2. 第21行是$image=$_FILES['image']['name'];
  3. 如何处理这一行:(

    <form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="image" id="image" size="40">
    <input name="" type="submit" value="upload" />
    
    </form>
    <?php 
    $con = mysql_connect('localhost', '', ''); //Update hostname
    mysql_select_db("test", $con); //Update database name
    
    define ("MAX_SIZE","1000"); 
    function getExtension($str)
    {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
    }
    
    $errors=0;
    $image=$_FILES['image']['name'];
    if ($image) 
    {
        $filename = stripslashes($_FILES['image']['name']);
        $extension = getExtension($filename);
        $extension = strtolower($extension);
        if ( ($extension != "jpg") && 
             ($extension != "jpeg") && 
             ($extension != "png") && 
             ($extension != "gif") && 
             ($extension != "JPG") && 
             ($extension != "JPEG") && 
             ($extension != "PNG") && 
             ($extension != "GIF") ) 
        {
            echo '<h3>Unknown extension!</h3>';
            $errors=1;
        }
        else
        {
            $size=filesize($_FILES['image']['tmp_name']);
    
            if ($size > MAX_SIZE*1024)
            {
                echo '<h4>You have exceeded the size limit!</h4>';
                $errors=1;
            }
    
            $image_name=time().'.'.$extension;
            $newname="images/".$image_name;
    
            $copied = copy($_FILES['image']['tmp_name'], $newname);
            if (!$copied) 
            {
                echo '<h3>Copy unsuccessfull!</h3>';
                $errors=1;
            }
            else echo '<h3>uploaded successfull!</h3>';
    
            mysql_query("insert into list (image) values('".$newname."')");
        }
    
        //Display image
        $rs=mysql_query("select * from list");
        if($rs)
            while($row=mysql_fetch_array($rs))
            {
             ?>
             <img width="150" src="<?php echo $row['image'];?>"><br>
             <?php 
            }
    }
    ?>
    
  4. 有什么想法吗?

2 个答案:

答案 0 :(得分:1)

当未定义任何数组变量索引时,会出现此通知Notice: Undefined index:

在这里使用isset

if(isset($_FILES['image']))
{
    $image=$_FILES['image']['name'];
    //your rest of code here
}

答案 1 :(得分:0)

Use php isset()

if(isset($_FILES['image']))
{
  // your code 
}