Solved

php while loop counter not incrementing

Posted on 2010-08-29
10
374 Views
Last Modified: 2012-05-10
Hello,

I'm trying to use the $counter variable as a counter so that it keeps track of how many times the while loop gets executed and then uses that value in my sql statement.  $counter is always 1 in both the sql statement and when I echo "pre=".$counter;.  I know the while loop is getting executed 4 times.  Any ideas?

if ($handle = opendir($upload_directory_from)){
			$counter = 1;
			$orig_w = 450;
			while (false !== ($file = readdir($handle))){
				if($file != '.' && $file != '..'){
					$fileparts  = array();
					$fileparts = explode(".",$file);
					$fileext = $fileparts[1];
					list($width, $height) = getimagesize($upload_directory_from.$file);
					$orig_h = ($height/$width)*$orig_w;
					$src = '';
					if (strtolower($fileext) == 'png') {
						$src = imagecreatefrompng($upload_directory_from.$file);
					}
					else if(strtolower($fileext) == 'gif'){
						$src = imagecreatefromgif($upload_directory_from.$file);
					}
					else if(strtolower($fileext) == 'jpg'){
						$src = imagecreatefromjpeg($upload_directory_from.$file);
					}
					else{
						echo "File type not supported, .gif, .jpg or .png required!";
					}	
					$tmp = imagecreatetruecolor($orig_w, $orig_h);
					imagecopyresampled($tmp, $src,                  0,0,0,0,$orig_w,$orig_h,$width,$height);
					if (strtolower($fileext) == 'png') {
						imagepng($tmp,$upload_directory_to.$file,100);
					}
					else if(strtolower($fileext) == 'gif'){
						imagegif($tmp,$upload_directory_to.$file,100);
					}
					else if(strtolower($fileext) == 'jpg'){
						imagejpeg($tmp,$upload_directory_to.$file,100);
					}
					else{
						echo "File type not supported, .gif, .jpg or .png required!";
					}						
					imagedestroy($tmp);
					imagedestroy($src);
					unlink($upload_directory_from.$file);
					$con = mysql_connect('localhost', 'musicopus1', 'octopus1');
					if (!$con){
					  die('Could not connect: ' . mysql_error());
					}
					mysql_select_db("dmname", $con);
					mysql_query("INSERT INTO GALLERY_IMAGES (IMAGE_NAME, CAPTION, ALBUM_COVER, ALBUM_ID, ORDER_ID)
						VALUES ('$file', 'TEST', 'N', 1, ".$counter.")");
					mysql_close($con);
					echo "pre=".$counter;
					$counter = $counter + 1;
					echo "postr=".$counter;					
				}
			}
				closedir($handle);
			}
		
	

Open in new window

0
Comment
Question by:cgray1223
10 Comments
 

Author Comment

by:cgray1223
Comment Utility
lines of special attention are 2 and 46-51
0
 
LVL 82

Accepted Solution

by:
Dave Baldwin earned 100 total points
Comment Utility
You have it inside the 'if' statement, move it down below the '}' so it is only in the 'while'.
}
echo "pre=".$counter;
$counter = $counter + 1;
echo "postr=".$counter;					
			}

Open in new window

0
 

Author Comment

by:cgray1223
Comment Utility
The counter incrementor code is inside an if statement which is inside the while statement, so that should be ok correct?.  the echo statements get echoed out multiple times so I know it's hitting the $counter = $counter + 1; code but when it gets to the echo "pre=".$counter; its always 1.  The echo "postr=".$counter;       always shows 2.
0
 
LVL 9

Assisted Solution

by:Snarfles
Snarfles earned 100 total points
Comment Utility
Looks pretty clean to me... :/

Try changing the variable name and see if something is interfering with $counter specifically... eg change to $counter1
0
 

Author Comment

by:cgray1223
Comment Utility
that didn't make a difference either....
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 58

Assisted Solution

by:cyberkiwi
cyberkiwi earned 100 total points
Comment Utility
Can you try two things?

1, Rename it.  Instead of counter, make it just $c.
You might have $counter updated elsewhere since $counter is globally visible.

2, Instead of the line

echo "pre=".$counter;

use

var_dump($counter);

var_dump shows the variable type as well as the value.
0
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
I suggested moving the counter code to see if the 'if' statement wasn't being executed.  If you move it and get a different answer, then 'if' part isn't executing.
0
 
LVL 5

Assisted Solution

by:innotionent
innotionent earned 100 total points
Comment Utility
If it was me i'd do this.

take
$counter = $counter + 1;
and do
$counter++;
then echo
echo $counter;

give that  a try.
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 100 total points
Comment Utility
Wow, this would be a lot easier to debug if there were consistently indented control structures and some comments in the code.

Here is what I would suggest.  Add several echo or var_dump statements to the code so that you can see the steps as they are executed.

Add error_reporting(E_ALL) to the top of your script so you can see if there are any places that depend on undefined variables.

Test the mysql() functions for success and report the errors to the browser output stream.

You wrote, "I know the while loop is getting executed 4 times.  Any ideas?" -- but how do you know that?  What tells us that?

Also, I would recommend getting the connect and select out of the loop, but that should not be hurting your counter (unless these statements are failing and you are looking in the data base to find the counter).
if ($handle = opendir($upload_directory_from))
{
    $counter = 1;
    $orig_w = 450;
    while (false !== ($file = readdir($handle)))
    {
        if($file != '.' && $file != '..')
        {
            $fileparts  = array();
            $fileparts = explode(".",$file);
            $fileext = $fileparts[1];
            list($width, $height) = getimagesize($upload_directory_from.$file);
            $orig_h = ($height/$width)*$orig_w;
            $src = '';
            if (strtolower($fileext) == 'png')
            {
                $src = imagecreatefrompng($upload_directory_from.$file);
            }
            else if(strtolower($fileext) == 'gif')
            {
                $src = imagecreatefromgif($upload_directory_from.$file);
            }
            else if(strtolower($fileext) == 'jpg')
            {
                $src = imagecreatefromjpeg($upload_directory_from.$file);
            }
            else
            {
                echo "File type not supported, .gif, .jpg or .png required!";
            }
            
            $tmp = imagecreatetruecolor($orig_w, $orig_h);
            imagecopyresampled($tmp, $src, 0,0,0,0,$orig_w,$orig_h,$width,$height);
            
            if (strtolower($fileext) == 'png')
            {
                imagepng($tmp,$upload_directory_to.$file,100);
            }
            else if(strtolower($fileext) == 'gif')
            {
                imagegif($tmp,$upload_directory_to.$file,100);
            }
            else if(strtolower($fileext) == 'jpg')
            {
                imagejpeg($tmp,$upload_directory_to.$file,100);
            }
            else
            {
                echo "File type not supported, .gif, .jpg or .png required!";
            }
            
            imagedestroy($tmp);
            imagedestroy($src);
            unlink($upload_directory_from.$file);

            $con = mysql_connect('localhost', 'musicopus1', 'octopus1');
            if (!$con)
            {
                die('Could not connect: ' . mysql_error());
            }
            mysql_select_db("dmname", $con);
            mysql_query("INSERT INTO GALLERY_IMAGES (IMAGE_NAME, CAPTION, ALBUM_COVER, ALBUM_ID, ORDER_ID) VALUES ('$file', 'TEST', 'N', 1, ".$counter.")");
            mysql_close($con);
            echo "pre=".$counter;
            $counter = $counter + 1;
            echo "postr=".$counter;     
        }
    }
    closedir($handle);
}

Open in new window

0
 

Author Comment

by:cgray1223
Comment Utility
There was no problem with the counter as it was functioning as it should.  The php script that I was calling is getting executed per file being uploaded.  This script is called once per file being uploaded instead of processing the file upload queue together, thus the counter is always 1.  Appreciate the help!
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
This article discusses how to create an extensible mechanism for linked drop downs.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to dynamically set the form action using jQuery.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now