Yii多行插入

时间:2014-11-23 15:23:24

标签: php yii

我有这个代码的问题..当我发布3个图像时,脚本只在数据库中插入最后一个..我该如何解决这个问题? 这是我的代码:

<?php
function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}
$valid_formats = array("jpg", "png", "gif", "bmp");
$max_file_size = 1024*2220; //100 kb
$path = "galerija/"; // Upload directory
$count = 0;
$key = generateRandomString();
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
    // Loop $_FILES to execute all files
    foreach ($_FILES['files']['name'] as $f => $name) {     
        if ($_FILES['files']['error'][$f] == 4) {
            continue; // Skip file if any error found
        }          
        if ($_FILES['files']['error'][$f] == 0) {              
            if ($_FILES['files']['size'][$f] > $max_file_size) {
                $message[] = "Slika $name je pre velika!.";
                continue; // Skip large files
            }
            elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
                $message[] = "Ekstenzija $name nije valjana!";
                continue; // Skip invalid file formats
            } else { // No error found! Move uploaded files 
                if (move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$key.$name)){
                        $model->naziv = $key.$name;
                        $model->save();
                }
            }
        }
    }
}
?>

我想我应该在}之后添加一些代码{//没有发现错误,但我不知道:S

1 个答案:

答案 0 :(得分:1)

您需要每次创建一个实例,如下所示:

$model=new ModelName();
$model->naziv = $key.$name;
$model->save();