在文件上传操作期间将数据保存在 yii2 中的数据库中 [英] Saving data in the database in yii2 during file upload action

查看:23
本文介绍了在文件上传操作期间将数据保存在 yii2 中的数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个上传控制器,我也在其中执行将其他数据保存到数据库中.上传到文件夹的文件没问题,但不会在表格中保存其他详细信息

I have a upload controller where by am also performing saving other data to the database. The file uploading to the folder is okay but saving the other details in the table doesn't happen

controller code

$images = $_FILES['evidence'];
$success = null;

$paths= ['uploads'];

// get file names
$filenames = $images['name'];


// loop and process files
for($i=0; $i < count($filenames); $i++){
//$ext = explode('.', basename($filenames[$i]));
$target = "uploads/cases/evidence".DIRECTORY_SEPARATOR . md5(uniqid()); //. "." . array_pop($ext);
if(move_uploaded_file($images['name'], $target)) {
    $success = true;
    $paths[] = $target;
} else {
    $success = false;

    break;
}

echo $success;
}
// check and process based on successful status 
if ($success === true) {
        $evidence = new Evidence();
        $evidence->case_ref=$id;
        $evidence->saved_on=date("Y-m-d");
        $evidence->save();

$output = [];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];

foreach ($paths as $file) {
    unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}

//  return a json encoded response for plugin to process successfully
echo json_encode($output);

在执行 var_dump($evidence->save()) 之后,我得到一个布尔错误 false

After doing var_dump($evidence->save()) I get an error of Boolean false

推荐答案

您可能会遇到验证错误.检查 $errors 属性

You could have validation errors. Check $errors property

// check and process based on successful status 
if ($success === true) {
        $evidence = new Evidence();
        $evidence->case_ref=$id;
        $evidence->saved_on=date("Y-m-d");
        $retSave = $evidence->save();

        if($retSave == false)
        {
              var_dump($evidence->errors);
        }

$output = [];
}
....

这篇关于在文件上传操作期间将数据保存在 yii2 中的数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆