如何减少重复代码的代码行数。

时间:2016-09-07 05:55:59

标签: php function

我使用下面的代码将图像多次插入到数据库中,那么如何将此代码专门转换为简单的函数或类似的函数以便我可以减少代码行数?

include 'template_imagefunction.php';
if (!empty($_FILES["uploadedimage"]["name"])) {
    $file_name=$_FILES["uploadedimage"]["name"];
    $temp_name=$_FILES["uploadedimage"]["tmp_name"];
    $imgtype=$_FILES["uploadedimage"]["type"];
    $ext= GetImageExtension($imgtype);
    $imagename=date("d-m-Y")."-".time().$ext;
    $target_path = "category/".$imagename;
    if(move_uploaded_file($temp_name, $target_path)) {
        $sql=mysql_query("INSERT INTO `category` (`cat_name`, `parent`, `cat_status`,`cat_image`) VALUES ('$catname', '--', '$status','$target_path') ");
        header('Location: categoryylisting1.php');
    }
    else {
        exit("Error While uploading image on the server");
    } 
}

2 个答案:

答案 0 :(得分:1)

1)定义像这样的函数

function upload($_FILES)
{

if (!empty($_FILES["uploadedimage"]["name"])) {
    $file_name=$_FILES["uploadedimage"]["name"];
    $temp_name=$_FILES["uploadedimage"]["tmp_name"];
    $imgtype=$_FILES["uploadedimage"]["type"];
    $ext= GetImageExtension($imgtype);
    $imagename=date("d-m-Y")."-".time().$ext;
    $target_path = "category/".$imagename;
   if(move_uploaded_file($temp_name, $target_path)) {
      $sql=mysql_query("INSERT INTO `category` (`cat_name`, `parent`, `cat_status`,`cat_image`) VALUES ('$catname', '--', '$status','$target_path') ");
      header('Location: categoryylisting1.php');
}
else {
      exit("Error While uploading image on the server");
} 
  }

   }

2)使用参数

调用该函数
upload($_FILES);

答案 1 :(得分:0)

使用数组在单个函数中添加多个选项