Mysql PHP文件上传更新

时间:2015-08-03 19:36:12

标签: php mysql crud

我有来自update.php的以下代码。 Create.php工作得很好。当我尝试按ID更新查询时,我没有在update.php上看到图像文件,所以我必须再次上传文件。我怎么解决这个问题。我有一个上传文件夹,我上传图像并将随机生成的文件名保存到数据库中。

    $officer = $_POST['officer'];
    $date = $_POST['date'];
    $complaint = $_POST['complaint'];
    $injured_name = $_POST['injured_name'];
    $owner_name = $_POST['owner_name'];
    $description = $_POST['description'];       

    //To be able to upload file to 'uploads/' folder all file related files. 
    $file = rand(1000,100000)."-".$_FILES['file']['name'];
    $file_loc = $_FILES['file']['tmp_name'];
    $file_size = $_FILES['file']['size'];
    $file_type = $_FILES['file']['type'];
    $folder="uploads/";

    // new file size in KB
    $new_size = $file_size/1024;  
    // new file size in KB
    // make file name in lower case
    $new_file_name = strtolower($file);
    // make file name in lower case

    $final_file=str_replace(' ','-',$new_file_name);



        $pdo = Database::connect();
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "UPDATE incidents SET officer = ?, date = ?, complaint =?, injured_name = ?, owner_name =?, description =?, file =?, type =?, size =?) WHERE id =?";
        $q = $pdo->prepare($sql);
        $q->execute(array($officer, $date, $complaint, $injured_name, $owner_name, $description, $final_file, $file_type, $new_size, $id));
        Database::disconnect();
        header("Location: incidents.php");

     }

 else {
    $pdo = Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "SELECT * FROM incidents where id = ?";
    $q = $pdo->prepare($sql);
    $q->execute(array($id));
    $data = $q->fetch(PDO::FETCH_ASSOC);
    $officer = $data['officer'];
    $date = $data['date'];
    $complaint = $data['complaint'];
    $injured_name = $data['injured_name'];
    $owner_name = $data['owner_name'];
    $description = $data['description'];
    $file = $data['file'];

    Database::disconnect();
}

我的表格是

    <div class="field">
                    <label class="upload" for="uploads">
                        <div class="btn">

                            <input name="file" placeholder="file upload" type="file" id="file" required value="<?php echo !empty($file)?$file:'';?>"/></div>
                    </label>
                </div>

我是PHP的新手,请原谅我,如果有一个简单的解决方案。我感谢您的帮助。感谢

1 个答案:

答案 0 :(得分:0)

如果您要上传文件,则需要移动该文件。然后在您的数据库中设置上传文件的新名称(更新)。

$final_file=str_replace(' ','-',$new_file_name);
// moving the file.
move_uploaded_file($file_loc,$folder . $final_file);