• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1645
  • Last Modified:

Uploading Images to a Category/SubCategory with PHP/MySQL

Okay - I'm attempting to create an 'admin' section of my website so I can upload my images into a category or appropriate subcategory instead of having to manually add them/code them on the HTML pages....

I have three tables:

icon_categories, icon_subcats, icon_images.

the categories table has 'cat_id' and 'cat_name', icon_subcats has 'sub_id', 'sub_name', 'cat_id', and the icon_images table has 'icon_id', 'icon_filename', 'icon_caption', 'cat_id', 'sub_id'.

I want to have two drop down boxes, the file field to upload the image, and then a text field to input the caption.

The first drop down box will be categories, and will be populated from the mysql database. The second drop down will be subcats - and I want it to populate with the subcats that match the original category selected. (IE When I select the 'movies' category, I want the second drop down to populate with all the subcats that go in movies).

That is what I'm having the first problem with. I've tried modifying several scripts... but finally just gave up. o.O

Then, I need the file to upload, I'm not picky about renaming or anything like that... I just need it to upload, and be stored in the database so that when I get around to coding the 'view' part of the album, I'll be able to pull it from there.

I don't need thumbnails, as all the images are only 100x100 pixels anyway.

Any help would be greatly appreciated... I'm pulling out my hair trying to figure out how this would work.
0
ReekaJean
Asked:
ReekaJean
  • 4
  • 4
1 Solution
 
ldbkuttyCommented:
Regarding dynamic dropdown box, you can use with Javascript or PHP. Javascript is client side solution and does not need to be reloaded, but it might have been disabled by the user. PHP is serverside solution and needs to be reloaded when a selection is made.

Storing the images in files is less complex and faster than database blobs. Upload the images to a common folder in the system and store the path in the database.

Tell me which of these you prefer.
0
 
ReekaJeanAuthor Commented:
I'm really not picky on the javascript/php option. This is only going to be used by me as an easier means of uploading my graphics/zip files and keeping them organised. So as far as that goes - just whichever way you think would be better/easier.

And I did want the files to be stored on the server. The image directory is /icons/ for these in particular... I just want the filename to be stored in the mysql so it will be easier for me to pull them back out in table form later on. :)

I wasn't going to worry about having seperate folders for each cateogry/subcat.... so something will need to be done to make sure the images aren't being named the same thing... either by keeping my original filename or just making sure that the php doesn't name them something that's already there.

But if I can get this working - I won't be adding any of the images myself... I'll be doing it all through the upload/gallery thing that I'm trying to build....

so like, I'd have icons/ and then *all* the graphics that I've uploaded will be stored in that folder... the database will call the filename and my caption as well as whichever category/subcategory ID that i've placed them in.
0
 
ldbkuttyCommented:
can you post the table structure + some related data's (as .sql statements) so I can give you direct solution.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
ReekaJeanAuthor Commented:
Alright.... this is in php form, so if you save it and run it - it should populate everything. This creates the three tables that I've currently got set, and adds the categories and subcats that I have so far. I don't have any images uploaded yet - so the image table is still blank. :)

----------------------------
mysql_query("CREATE TABLE icon_categories(
                                    cat_id INT NOT NULL AUTO_INCREMENT,
                                    cat_name VARCHAR(255),
                                    PRIMARY KEY (cat_id)
                        )") or die ("Table Creation Error." .mysql_error());

mysql_query("CREATE TABLE icon_subcats(
                                    sub_id INT NOT NULL AUTO_INCREMENT,
                                    sub_name VARCHAR(255),
                                    cat_id INT(20) NOT NULL,
                                    PRIMARY KEY (sub_id),
                                    KEY (cat_id)
                        )") or die("Table Creation Error." .mysql_error());
                        
mysql_query("CREATE TABLE icon_images(
                                    icon_id INT NOT NULL AUTO_INCREMENT,
                                    icon_filename VARCHAR(255),
                                    icon_caption TEXT,
                                    cat_id INT(20) NOT NULL,
                                    sub_id INT(20),
                                    PRIMARY KEY (icon_id),
                                    KEY (cat_id),
                                    KEY (sub_id)
                        )") or die ("Table Creation Error." .mysql_error());

mysql_query("INSERT INTO icon_categories (cat_name) VALUES ('Movies'), ('Music'), ('Actors'), ('Actresses'), ('Misc')") or die("Could not populate database." .mysql_error());

mysql_query("INSERT INTO icon_subcats(sub_name, cat_id) VALUES ('Harry Potter', 1), ('Lord of the Rings', 1), ('Phantom of the Opera', 1), ('Star Wars', 1), ('Johnny Depp', 3), ('Orlando Bloom', 3), ('Alan Rickman', 3), ('Drew Barrymore', 4), ('Angelina Jolie', 4), ('Humour', 5), ('Animals', 5), ('Holidays', 5)") or die("Could not populate database." .mysql_error());

0
 
ldbkuttyCommented:
Here's your script:

<?php

$hostname = "localhost";
$host_user = "root";
$host_pass = "****";
$database_name = "****";

$uploaddir = 'uploads/'; // Change with your folder path to upload the files.

// Connect to MySql
$link = mysql_connect($hostname, $host_user, $host_pass) or die('Could not connect: ' . mysql_error());

// Select the database
mysql_select_db($database_name, $link) or die('Could not select db: ' . mysql_error());

if(array_key_exists('Submit', $_POST) && !empty($_POST['Submit']))
{
      $cat_id = $_POST['category'];
      $subcat_id = $_POST['subject'];
      $file_caption = $_POST['caption'];
      
      $uploadfile = $uploaddir . $_FILES['img1']['name'];
      
      // Return error if the file-size is greater than 3 MB !
      if(($_FILES['img1']['size']) > 3072000)
      {
          echo "Sorry, File size is bigger than 3 MB";
          exit();
      }
      
       // let us read all the files in the directory and rename the file, if exists.
       if($handle = opendir($uploaddir))
       {      
             while(false !== ($file = readdir($handle)))
             {
                     if($file != "." && $file != "..")
                     {
                        // if samefile name exists already in the directory.
                        if(strtolower($file) == strtolower($_FILES['img1']['name']))
                        {
                              $file_ext = strrchr($_FILES['img1']['name'], ".");
                              // replace the uploading file with date() so it is unique.
                               $changed_file_name = basename($_FILES['img1']['name'], $file_ext) . '_' . date("YmdHis") . $file_ext;
                                 $uploadfile = $uploaddir . $changed_file_name;      
                        }      
                    }      
              }      
              closedir($handle);      
       }
       print "<pre>";
      
       if(move_uploaded_file($_FILES['img1']['tmp_name'], $uploadfile))
       {      
            chmod($uploadfile, 0777);
            $query = "INSERT INTO icon_images(icon_id, icon_filename, icon_caption, cat_id, sub_id) VALUES ('', '" . mysql_real_escape_string($uploadfile) . "', '$file_caption', $cat_id, $subcat_id)";
            mysql_query($query) or die("Insert query error: " . mysql_error() . ' ~~~ Query: ' . $query);
            print "File is was successfully uploaded and inserted in DB. <a href='$uploadfile'>Click here</a> to view the file";      
       }
       else
       {      
            print "Possible file upload attack!  Here's some debugging info:\n";
            print_r($_FILES);
            exit;
       }
        print "</pre>";
       exit();
}

$result = mysql_query("SELECT * FROM icon_categories LEFT JOIN icon_subcats ON icon_subcats.cat_id = icon_categories.cat_id") or die("Sql error: " . mysql_error());

?>

<script type="text/javascript">
var theCateg = Array();
</script>

<?php

$categ_array = array();
$i = 0;

while($row = mysql_fetch_array($result))
{
     if(!array_key_exists($row['cat_id'], $categ_array))
     {
          $categ_array[$row['cat_id']] = $row['cat_name'];    
     }
     
?>

<script type="text/javascript">
 theCateg[<?=$i?>] = new Array();
 theCateg[<?=$i?>] = ["<?=$row['cat_id']?>", "<?=$row['cat_name']?>", "<?=$row['sub_id']?>", "<?=$row['sub_name']?>"];
</script>

<?php

     $i++;
}

?>

<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" onsubmit="return validateForm(this)">
<select name="category" onChange="categorySelected(this)">
<option value="">=>Please Select<=</option>

<?php

foreach($categ_array as $key => $value)
{
     $selected = (isset($_POST['category']) && $_POST['category'] == $key) ? 'selected="selected"' : '';
     echo "<option value='$key' $selected> $value </option>";
}

?>

</select>
<select name="subject">
<option value="">=>Please Select<=</option>
</select>
<br /><br />
File: <input type="file" name="img1" value="" /> <br /><br />
Caption: <input type="text" name="caption" value="" /> <br /><br />
<input type="submit" name="Submit" value="Submit" />
</form>

<script type="text/javascript">
function categorySelected(theSel){
 theForm = theSel.form;
 sOpt = theForm.subject.options;
 sOpt.length = 0;
 sOpt[sOpt.length] = new Option("=>Please Select<=", "");
 cOpt = theForm.category.options;
 if(theSel.options[theSel.selectedIndex].value=="") return false;
 for(i=0; i<theCateg.length; i++){
  if(theCateg[i][0] == theSel.options[theSel.selectedIndex].value){
   sValue = theCateg[i][2];
   sName  = theCateg[i][3];
   if(sValue>""){
    sOpt[sOpt.length] = new Option(sName, sValue);
   }
  }    
 }
}

function validateForm(theForm){
 if(theForm.category.selectedIndex == 0){
  alert("Please select the category");
  return false;      
 }      
 if(theForm.subject.selectedIndex == 0){
  alert("Please select the sub category");
  return false;      
 }      
 if(theForm.img1.value == ""){
  alert("Please upload a image");
  return false;      
 }
 if(!theForm.img1.value.match(/\.(gif|jpg|jpeg|bmp|png)/i)){
  alert("Please upload only valid image format file");
  return false;
 }
 return true;
}
</script>
0
 
ReekaJeanAuthor Commented:
Only one problem.... I've got this in the admin section of my site...

The path to the icons directory is up one level, and the ../icons/ isn't working. o.O

Is there something special I need to do so it reads the path instead of thinking the two dots are supposed to be there? lol.

And thank you so much for this by the way. ^^
0
 
ldbkuttyCommented:
Is the "icons" a directory placed one level up for the current php file ? If yes, that should work.

Just for information,

This path will take you to a file within the same directory :
<img src="picture_name.jpg" />

This path will take you one directory back :
<img src="../directory_name/picture_name.jpg" />

This path will take you two directories back :
<img src="../../directory_name/picture_name.jpg" />

Or you can give full URL for testing.
0
 
ReekaJeanAuthor Commented:
Ah. Thank you. It was a typo on my part. lol.

Sometimes it just takes someone else to say something before you see it. hehehe.

Thank you so much! :)
0
 
ravikesh yadavCommented:
rtrtrfgf6trrtewews
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 4
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now