1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Image Manager Bugs

Discussion in 'PHP' started by Jeremy Benson, Jul 9, 2014.

  1. #1
    Hey,

    I'm working on an image manager, but I can't seem to add photos to an existing album. I've got this one function that creates an album if it hasn't been created, and one that should fire if the user is trying to add photos to an existing album. The problem is I seem to always end up in the function that creates an album. I've got a block in there that sends the user back to their dashboard if the album already exists(I'll take that out after).. That's what keeps happening.

    As far as I can tell I keep ending up in that first block in the last if statement.

    
    if($_POST['editType'] == "managephotos")
    {
      
       $albumName = $_POST['albumName'];
       $retrievedInfo = [];
      
       //Count the amount of name elements there are in $_FILES
      
       $limit = count($_FILES['imageFiles']['name']);
        
       $fileHelper = new cfile;
       $fileHelper->process_files($_FILES, $limit, "img");
      
       //Test if album name exists if it exists add photos else create album
       $dbConnect = new cdbconnect;
      
       $dbConnect->select("SELECT `albumName` FROM `photoalbums` WHERE `userName` =  ? AND `albumName` = ?", [$albumName, $user->return_username()]);
       $retrievedInfo = $dbConnect->get();
      
       if(empty($retrievedInfo) || $retrievedInfo[0] == "")
       {
         $fileHelper->make_photoalbum($albumName);
      
       }else{
      
         //update album.
        
         $fileHelper->update_photoalbum($albumName);
      
       }
    
    }
    
    PHP:
     
    Jeremy Benson, Jul 9, 2014 IP
  2. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #2
    Uhm, try switching around $albumName and $user->return_username() in the query...
     
    PoPSiCLe, Jul 10, 2014 IP
  3. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #3
    That was such a stupid bug. I found that when I got home, but there's one other thing that isn't working.
     
    Jeremy Benson, Jul 10, 2014 IP
  4. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #4
    That bug was dumb. I found it when I got home, but there's another giving me some trouble. Not sure if I can find this one... I've got an onclick function on a div that opens the photo album when clicked, and changes photos. Right now when I click the album all the pictures show alternate text.

    The following javascript function calls the php script below.

    function change_photoalbum(IDSet)
    {
    
        var id = IDSet;
       
        var idData = {"IDSet":id, "from":"dashboard"};
       
        var output = Array();
       
        $.ajax({
            "type":"POST",
            "url":"../mechanics/scripts/php/getphotoalbum.php",
            "dataType":"html",
            data:idData,
            "success":function(data){
           
                output = data.split(',');
               
                window.document.getElementById('albumnameoutput').innerHTML = (output[1]);
                window.document.addalbumform.albumName.value = (output[1]);
               
                window.document.getElementById('albumimage1').innerHTML = "";
                window.document.getElementById('albumimage2').innerHTML = "";
                window.document.getElementById('albumimage3').innerHTML = "";
                window.document.getElementById('albumimage4').innerHTML = "";
                window.document.getElementById('albumimage5').innerHTML = "";
                window.document.getElementById('albumimage6').innerHTML = "";
                window.document.getElementById('albumimage7').innerHTML = "";
                window.document.getElementById('albumimage8').innerHTML = "";
                window.document.getElementById('albumimage9').innerHTML = "";
                window.document.getElementById('albumimage10').innerHTML = "";
                window.document.getElementById('albumimage11').innerHTML = "";
                window.document.getElementById('albumimage12').innerHTML = "";
               
                if(data != "")
                {
                    alert(data);
                   
                    if(output[2] != "")
                    {                                                               
                        window.document.getElementById('albumimage1').innerHTML = "<img height=\"120\" width=\"90\" alt=" + output[2] +" src=\"users/"+ output[0] +"/images/albums/" + output[1] + "/" + output[2].substring(0, output[2].indexOf('.')) + "_tmb" + output[2].substring(output[2].indexOf('.'), output[2].length) + "\" />";
                    }
                    if(output[3] != "")
                    {
                        window.document.getElementById('albumimage2').innerHTML = "<img height=\"120\" width=\"90\" alt=" + output[3] +" src=\"users/"+ output[0] +"/images/albums/" + output[1] + "/" + output[3].substring(0, output[3].indexOf('.')) + "_tmb" + output[3].substring(output[3].indexOf('.'), output[3].length) + "\" />";
                    }
                    if(output[4] != "")
                    {
                        window.document.getElementById('albumimage3').innerHTML = "<img height=\"120\" width=\"90\" alt=" + output[4] +" src=\"users/"+ output[0] +"/images/albums/" + output[1] + "/" + output[4].substring(0, output[4].indexOf('.')) + "_tmb" + output[4].substring(output[4].indexOf('.'), output[4].length) + "\" />";
                    }
                    if(output[5] != "")
                    {
                        window.document.getElementById('albumimage4').innerHTML = "<img height=\"120\" width=\"90\" alt=" + output[5] +" src=\"users/"+ output[0] +"/images/albums/" + output[1] + "/" + output[5].substring(0, output[5].indexOf('.')) + "_tmb" + output[5].substring(output[5].indexOf('.'), output[5].length) + "\" />";
                    }
                    if(output[6] != "")
                    {
                        window.document.getElementById('albumimage5').innerHTML = "<img height=\"120\" width=\"90\" alt=" + output[6] +" src=\"users/"+ output[0] +"/images/albums/" + output[1] + "/" + output[6].substring(0, output[6].indexOf('.')) + "_tmb" + output[6].substring(output[6].indexOf('.'), output[6].length) + "\" />";
                    }
                    if(output[7] != "")
                    {
                        window.document.getElementById('albumimage6').innerHTML = "<img height=\"120\" width=\"90\" alt=" + output[7] +" src=\"users/"+ output[0] +"/images/albums/" + output[1] + "/" + output[7].substring(0, output[7].indexOf('.')) + "_tmb" + output[7].substring(output[7].indexOf('.'), output[7].length) + "\" />";
                    }
                    if(output[8] != "")
                    {
                        window.document.getElementById('albumimage7').innerHTML = "<img height=\"120\" width=\"90\" alt=" + output[8] +" src=\"users/"+ output[0] +"/images/albums/" + output[1] + "/" + output[8].substring(0, output[8].indexOf('.')) + "_tmb" + output[8].substring(output[8].indexOf('.'), output[8].length) + "\" />";
                    }
                    if(output[9] != "")
                    {
                        window.document.getElementById('albumimage8').innerHTML = "<img height=\"120\" width=\"90\" alt=" + output[9] +" src=\"users/"+ output[0] +"/images/albums/" + output[1] + "/" + output[9].substring(0, output[9].indexOf('.')) + "_tmb" + output[9].substring(output[9].indexOf('.'), output[9].length) + "\" />";
                    }
                    if(output[10] != "")
                    {
                        window.document.getElementById('albumimage9').innerHTML = "<img height=\"120\" width=\"90\" alt=" + output[10] +" src=\"users/"+ output[0] +"/images/albums/" + output[1] + "/" + output[10].substring(0, output[10].indexOf('.')) + "_tmb" + output[10].substring(output[10].indexOf('.'), output[10].length) + "\" />";
                    }
                    if(output[11] != "")
                    {
                        window.document.getElementById('albumimage10').innerHTML = "<img height=\"120\" width=\"90\" alt=" + output[11] +" src=\"users/"+ output[0] +"/images/albums/" + output[1] + "/" + output[11].substring(0, output[11].indexOf('.')) + "_tmb" + output[11].substring(output[11].indexOf('.'), output[11].length) + "\" />";
                    }
                    if(output[12] != "")
                    {
                        window.document.getElementById('albumimage11').innerHTML = "<img height=\"120\" width=\"90\" alt=" + output[12] +" src=\"users/"+ output[0] +"/images/albums/" + output[1] + "/" + output[12].substring(0, output[3].indexOf('.')) + "_tmb" + output[12].substring(output[12].indexOf('.'), output[12].length) + "\" />";
                    }
                    if(output[13] != "")
                    {
                        window.document.getElementById('albumimage12').innerHTML = "<img height=\"120\" width=\"90\" alt=" + output[13] +" src=\"users/"+ output[0] +"/images/albums/" + output[1] + "/" + output[13].substring(0, output[13].indexOf('.')) + "_tmb" + output[13].substring(output[13].indexOf('.'), output[13].length) + "\" />";
               
                    }       
                }
            }
        });
    }
    
    Code (JavaScript):
    
    <?php
    
       require('../../../mechanics/data/sqldata.php');   
       require('../../../mechanics/scripts/classes/php/cdbconnect.php');
         
       $albumID = $_POST['IDSet'];
       $albumName = "";
       $retrievedInfo = [];
       $totalViews = 0;
       
       $returnString = "";
       
       $dbConnect = new cdbconnect;
       $dbConnect->select_all("SELECT `userName`, `albumName`, `photo1name`, `photo2name`, `photo3name`, `photo4name`, `photo5name`, `photo6name`, `photo7name`, `photo8name`, `photo9name`, `photo10name`, `photo11name`, `photo12name`, `albumViews` FROM `photoalbums` WHERE `ID` = ?", [$albumID]);
       
       $retrievedInfo = $dbConnect->get_all();   
       
       //Update views
       if($_POST['from'] != "dashboard")
       {
       
         $totalViews = $retrievedInfo[0]['albumViews'] + 1;
       
         $dbConnect->update("UPDATE `photoalbums` SET `albumViews` = ? WHERE `ID` = ?", [$totalViews, $albumID]);
       
       }else{
       
       
         $totalViews = $retrievedInfo[0]['albumViews'];
       
       }
       
       //Send information back to profile.
       
       for($i = 0; $i <= 13; $i++)
       {
       
         $returnString = $returnString . $retrievedInfo[0][$i] . ',';
       }   
       
       $returnString = substr($returnString, 0, strlen($returnString) - 1);
       
       echo $returnString;
    
    ?>
    
    PHP:
     
    Jeremy Benson, Jul 10, 2014 IP
  5. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #5
    Hard to say, but that javascript function really should use a loop - there's a lot of unnecessary code in that callback. Check to see what gets returned via Firebug, or similar, and see if there is anything wrong with the input that's supposed to get parsed in the output.
     
    PoPSiCLe, Jul 10, 2014 IP
  6. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #6
    Not sure what you mean by using a loop... lol, I hear things, but don't really know what is meant... The string returned by the php script is as follows...

    Famous4, test2, jeremy.jpg, DarkFoil.jpg, BlackandWhiteSticker - Copy.jpg, BlackandWhiteSticker.jpg, DarkFoil.jpg, myspace profile.jpg, NewPoliticalAgendaCover.jpg, PhilosophiesCover.jpg, picture001.jpg, picture002.jpg, picture006.jpg, picture007 - Copy.jpg

    As far as I can tell that's exactly right. That's all twelve images in the album preceded by username, and album name. I'll check firebug tonight and post what that's saying..
     
    Jeremy Benson, Jul 10, 2014 IP
  7. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #7
    Well, since you get the alt-text, but not the image, the image-src/url is probably not correct. I'd check to see what gets output in the img-element.
     
    PoPSiCLe, Jul 10, 2014 IP
  8. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #8
    When I got home I looked at the links. There is something strange going on. If Firebug I get... Shoot I was gonna show you the link but my recent copy of the site is on a flash drive at home. I'll pseudo what's happening if it helps.

    I'm supposed to get a link like this...

    users/Famous4/images/albums/albumname/image1.jpg

    but I'm getting something like this...

    users/EBF%%EBFFamous4/images/albums/albumname/image1.jpg

    It's putting some kind of weird string before the username. Not sure if it's a memory address, or something, don't have a clue..
     
    Jeremy Benson, Jul 11, 2014 IP
  9. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #9
    I think it might have to do with your quotes in the strings.
    Instead of escaping all the double quotes, you're not escaping some...
    Try redoing the string concoctions like this:
    
    window.document.getElementById('albumimage5').innerHTML = '<img height="120" width="90" alt="' + output[6] +'" src="users'+ output[0] +'/images/albums/' + output[1] + '/' + output[6].substring(0, output[6].indexOf('.')) + '_tmb' + output[6].substring(output[6].indexOf('.'), output[6].length) + '" />';
    
    Code (markup):
    Change the numbers as needed, of course
     
    PoPSiCLe, Jul 11, 2014 IP
  10. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #10
    Awesome. I'll try that when I get home :) Thanks again.
     
    Jeremy Benson, Jul 11, 2014 IP
  11. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #11
    lol, I signed into digital point and saw that sign with the car driving off the road, and was like that's where my projects headed, lol.

    This is weird. I wrote all the strings out as you have them in single quotes. I still get alt text, but now Firebug doesn't throw errors. I took one of the strings and took out all the variables out and wrote in what would be interpolated and the path was a perfect match to what it is when I just put an image tag in the html code and the image shows. I put the two string paths in notepad and scratched my head for awhile trying to find the difference. After that I took the strings and wrote a mini program to test a tripple equal comparison. They didn't match, but yet they were identical. I saved the notepad file and got a unicode character warning. I figured the code had characters in it, so I took all the code that would make paths to the images and put them in notepad, but they saved without any unicode warning. I don't know if the unicode characters got in there while I was backspacing the variables to write in what would be interpolated, or if it was already in the code...
     
    Jeremy Benson, Jul 14, 2014 IP
  12. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #12
    That is weird, but it might have something to do with how the files are saved (which character encoding) and how the data is being pulled from a database (and which character encoding you're using in your db).
    I say always go for UTF-8 or similar, never trust anything Win-specific. And make sure that all connections to the DB are made with the same character encoding as the output files.
     
    PoPSiCLe, Jul 14, 2014 IP
  13. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #13
    1) Why are you adding a trailing slash to the thumbnail name?

    2) I'd really suggest using 'lastIndexOf' instead of 'indexOf' to find the extension 'break'.

    3) You're in a programming language, use a loop instead of redundant code.

    4) It's usually faster executing if you only do the getElementById once at the start and store them in an array.

    5) You should REALLY be using the DOM instead of the sloppy innerHTML mess.

    6) generally one should only have to say "document", not "window.document"

    Guessing wildly, but:
    function change_photoalbum(IDSet) {
     
    	var
    		id = IDSet,
    		idData = {
    			"IDSet" : id,
    			"from" : "dashboard"
    		},
    		output = [],
    		targets = [],
    		d = document;
    		
    	for (var t = 1; t < 14; t++) {
    		targets.push(d.getElementById('albumImage' + t));
    	}
    	
    	function flush(e) {
    		while (e.firstChild) e.removeChild(e.firstChild);
    	}
    	
    	function make(tagName, contents, attribs, parent) {
    		var e = d.createElement(tagName);
    		if (contents) e.appendChild(
    			typeof contents == 'object' ? contents : d.createTextNode(contents)
    		);
    		if (attribs) for (var i in attribs) e[i] = attribs[i];
    		if (parent) parent.appendChild(e);
    		return e;
    	}
    		
    	$.ajax({
    		type : "POST",
    		url" : "../mechanics/scripts/php/getphotoalbum.php",
    		dataType : "html",
    		data : idData,
    		"success" : function(data) {
    			for (var t = 0; t < target.length; t++) e.flush(targets[t]);
    		 
    			if (data != "") {
    				output = data.split(',');
    				d.getElementById('albumnameoutput').innerHTML = output[1];
    				d.addalbumform.albumName.value = output[1];
    				alert(data);
    				
    				var
    					path = 'users/' + output[0] + 'images/albums/' + output[1] + '/';
    				
    				for (var t = 0; t < targets.length; t++) {
    					var
    						name = output[t + 2],
    						extPos = name.lastIndexOf('.'),
    					make('img', false, {
    						height : '120',
    						width : '120',
    						alt : name,
    						src : path + name.substring(0, extPos) +
    							'_tmb' + name.substring(extPos)
    					}, targets[t]);
    				}
    			}
    		}
    	});
    }
    Code (markup):
    Heading to bed so I've not dug into your PHP too deep, but tomorrow I'll try to put together a quick demo of this to show what I mean.... though that dbconnect object looks too complex for it's own good and/or redundant to what mysqli or PDO can already do. Also the 'stuff the entire query and it's associated data onto a single line' bit can't be making your life any easier either... much less that memory wasting '$returnstring' nonsense.
     
    deathshadow, Jul 15, 2014 IP
  14. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #14
    Ah the sql object just runs queries as it normally would. There's an array for getting one value with fetch, and a multidimensional array for getting more values. I use select, select_all,get, get_all functions for each type. I like it cuz it cut down the code in the front end files...

    As for that code it looks good, but I can only half understand it... I'll try to study it a bit more. I'm confused about the part here..

    
    function make(tagName, contents, attribs, parent) {
      var e = d.createElement(tagName);
      if (contents) e.appendChild(
      typeof contents == 'object' ? contents : d.createTextNode(contents)
      );
      if (attribs) for (var i in attribs) e[i] = attribs[i];
      if (parent) parent.appendChild(e);
      return e;
      }
    
    Code (markup):
    Does it matter that I already have div objects in my html where I plan on placing the images? It just looks like here it's creating elements?
     
    Jeremy Benson, Jul 15, 2014 IP
  15. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #15
    Sounds like you'd be better off just using PDO the way PDO works -- though methods like "get all" or even pdo's ::fetchAll introduce so much memory overhead, you're usually best off just saying "no" to it. Dumping the entire result set into an array is just a waste of memory AND processing time.

    Besides, is it really such a big deal to type:
    $statement = $db->prepare('
    	SELECT
    		userName, albumName,
    		photo1name, photo2name, photo3name, photo4name, photo5name, photo6name,
    		photo7name, photo8name, photo9name, photo10name, photo11name, photo12name,
    		albumViews
    	FROM photoalbums
    	WHERE ID = ?
    ');
    $db->execute([$albumID]);
    Code (markup):
    Instead of what you were doing? I mean, looking at what you were doing, why not:
    <?php
     
    /* assuming $db is a connected PDO object */
    
    $albumStmt = $db->prepare('
    	SELECT
    		userName, albumName,
    		photo1name, photo2name, photo3name, photo4name, photo5name, photo6name,
    		photo7name, photo8name, photo9name, photo10name, photo11name, photo12name,
    		albumViews
    	FROM photoalbums
    	WHERE ID = ?
    ');
    $albumStmt->execute([$_POST['IDSet']]);
    
    if ($albumInfo = $albumStmt->fetch()) {
    
    	if ($_POST['from'] != "dashboard") {
    		$updateStmt = $db->prepare('
    			UPDATE photoalbums
    			SET albumViews = ?
    			WHERE ID = ?
    		');
    		$updateStmt->execute([ ++$albumInfo['albumViews'], $_POST['IDSet']);
    	}
    	
    	// Send information back to profile.
    	echo implode(',', $albumInfo);
    	
    } else {
    	// you should really have a 0 matching rows handler here!
    }
     
    ?>
    Code (markup):
    Not really seeing how adding more overhead is saving you anything there...

    Though I do have a big question... are you really sure you want to hard-code the number of possible images? I mean, we have RELATIONAL databases for a reason. I mean why not have one table for users, one table for albums, and one table for photos?

    users:
    id (unique, auto-increment)
    name
    other info

    albums:
    id (unique, auto-increment)
    user_id (indexed)
    name
    views

    photos:
    id (unique, auto-increment)
    album_id (indexed)
    name

    Ends up more queries, but of smaller tables... and means an album could have any number of images. Would also be easier to process client or server-side.

    Generally hard-coding fixed-numbers of items will bite you sooner or later.

    Well, lemme go through piece by piece and explain it.

    I create a 'd' elemement just to make it a bit less unwieldy with all the times we call document. The 'targets' array gets filled with your albumimage DIV. (though I think I miscounted/misaligned to your logic).

    The flush function does the same thing as innerHTML = ''; except that it doesn't force a reflow/reparse of the page. As a rule innerHTML should be avoided unless you REALLY need it. Manipulating the DOM is faster running, smoother showing and in general a superior way of doing things.

    The make function does indeed just make a new element and plug contents (either as a object or text) and attributes onto it. Pay attention to 'parent' -- if you pass that value, the 'appendChild' method plugs the newly created element into that one. Basically, this ALSO replaces the innerchild="<img>" you were using -- again manipulating the DOM instead.

    In the 'success' method we just go through and 'flush' the contents of all the elements we stored in the target array -- those would be your DIV you want to plug the images into.

    I store the path beforehand as it's used more than once. Any operations you use more than once should be pre-done so you aren't repeating doing the same thing over and oer again -- likewise if you can do something outside the loop should be done so as to speed up execution. Hence why I do the same for the name and position of the period.

    Though - oops, typo. Should be a semi-colon not a comma after extPos. What I get for typing it into the post box and not testing :D

    We then just call the make function to create a whole new IMG tag, and plug it into the appropriate DIV from the targets array.

    Though again, I was guessing as I've got no clue what your markup looks like. If I were implementing something like this, I'd probably NOT have the multiple DIV, and instead have a single parent container into which I'd plug ALL the images, again using the DOM.

    I'd probably also swing an axe at what I can only assume is jQuery, since it's taking too much control out of your hands on this; and 99% of the time is pointless slow code bloat that has no business on a website in the first place.
     
    deathshadow, Jul 15, 2014 IP