Jaymin
Jaymin

Reputation: 1661

How to reduce no of lines of code for repeating codes.?

I am using below code for inserting image into DB for many times, So how can I specifically convert this code into a simple function or maybe similar to that so that I can reduce my number of lines of codes?

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");
    } 
}

Upvotes: 1

Views: 65

Answers (2)

lndr
lndr

Reputation: 1

use array for adding multiple options in single function

Upvotes: 0

JYoThI
JYoThI

Reputation: 12085

1) define the function like this

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)call the function with parameter

upload($_FILES);

Upvotes: 1

Related Questions