在数据库中上传和插入图像链接时出现问题。

时间:2018-10-09 21:49:10

标签: php mysql forms file-upload

尝试上传图片和状态更新时出现问题。如果用户不想在状态旁边上传图像,它将完美地插入表格(Newsfeed)中,但是如果用户希望与图像一起添加图像,则会出现错误:未定义索引: img在...中 关于如何解决此问题的任何想法?

这里有我的HTML,他们可以在其中上传图像以及状态更新。

<form action="include/updatestatus.php" method="post">
 <div class="form-group">
  <label for="status">Status</label>
  <input type="text" class="form-control" name="status" id="status" placeholder="<?php echo $status;?>">
</div>
<!-- Single button -->
<p ><span class="glyphicon glyphicon-film"></span> Upload an Image?:
  <input type="file" name="img" class="btn btn-default">
</p>
<div class="text-right">
        <button type="submit" name="statusupdate" class="btn btn-default btn-md">
          <span class="glyphicon glyphicon-thumbs-up"></span> Update Status
        </button>
      </div>
</form>

在这里上传并插入php代码。 (包括/updatestatus.php)

<?php
if (isset($_POST['statusupdate'])) {
    $date = date("Y.m.d");
//If Post Image is blank --> insert with nothing.
if (empty($_POST['img'])) {
    // prepare sql and bind parameters
    $stmt = $DB_con->prepare("INSERT INTO newsfeed (userid, status,uploaddate)
    VALUES (:userid, :status, :date)");
    $stmt->bindParam(':userid', $_SESSION['user']['id']);
    $stmt->bindParam(':status', $_POST['status']);
     $stmt->bindParam(':date', $date);
    $stmt->execute();

    echo "New records created successfully";
    }
else {

 $name=$_FILES['img']['name'];
 $type=$_FILES['img']['type'];
 $size=($_FILES['img']['size'])/1024;

 $ext=end(explode('.',$name));
 if (($ext == "gif")
 || ($ext == "jpeg")
 || ($ext == "jpg")
 || ($ext =="png")
 || ($ext =="PNG")
 && ($size > 50))
 {
 //Changes Name to Number :)
 $newname=uniqid();
 $imagename=$newname.".".$ext;
 $directory="images/upload/";
 $fulldirectory=$directory.$imagename;
 if(move_uploaded_file($_FILES['img']['tmp_name'],$fulldirectory))
 {
   $stmt = $DB_con->prepare("INSERT INTO newsfeed (userid, status,uploaddate,image)
   VALUES (:userid, :status, :date, :image)");
       $stmt->bindParam(':userid', $_SESSION['user']['id']);
       $stmt->bindParam(':status', $_POST['status']);
      $stmt->bindParam(':date', $date);
      $stmt->bindParam(':image', $imagename);


 //If upload is a success --> Redirect to profile.php?action=upload.success
       if($stmt->execute()){
   header ('location: ../profile.php?action=upload.success');

       }
     else
       header ('location: ../profile.php?action=upload.failed');
     }
 else
 {
    header('location: ../profile.php?action=file.size');
 }
 }
 else{
     header('location: ../profile.php?action=wrong.extension');
     }
   } //end of first else
} //end of $_Post['statusupdate']
?>

2 个答案:

答案 0 :(得分:0)

尝试将enctype =“ multipart / form-data”添加到标记中。

要检查文件是否已上传,请执行以下操作:

if(!file_exists($_FILES['img']['tmp_name']) || !is_uploaded_file($_FILES['img']['tmp_name'])) {
    echo 'No upload';
}

答案 1 :(得分:0)

您的表单标签必须包含enctype="multipart/form-data"才能上传文件。

还要检查$_POST['img']永远不会存在,因为它包含图像数据的$_FILES数组