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.

small loop problem

Discussion in 'PHP' started by ameerulislam43, Dec 31, 2012.

  1. #1
    Having a loop problem.. I'm creating a nested loop to show images from my database 2/ row. With this code I was able to generate 2 images per row but the same image is appearing twice then the next image is going to the next line and showing it twice again.

    <!-- Table -->                        <div class="table">                                                    <div style="margin-left:50px;" id="images">                            <table width='100%' border='0' cellspacing='0' cellpadding='0'>                                                    <?php                                while($rows=mysql_fetch_array($result))                                {                                $link=$rows[company_logo];                                    $count=0;                                    echo "<tr>";                                                                        while($count<=1){                                                                                echo "<td><img src=\"upload/$link\" width=\"100px\" height=\"100px\"/></td>";                                            $count++;                                        }                                                                                                                        echo "</tr>";                                                                        }                                                                    ?>                                                                            </table>                                                            </div>
    PHP:
    I know what's wrong but don't know how to solve it.

    Thanks!
     
    ameerulislam43, Dec 31, 2012 IP
  2. yelbom

    yelbom Greenhorn

    Messages:
    36
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    16
    #2
    Can you re post your code again so its readable and not all on one line.
     
    yelbom, Dec 31, 2012 IP
  3. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #3
    I've got more questions than answers given the train wreck of bad code you've got... Specifically what the devil even makes that a table?!? Why are you using so many DIV?!? What's with the attributes like border and cellpadding that have zero business in any website written after 1997? You don't say 'px' on HTML properties... Why the improper/malformed/deprecated way of indexing arrays? Why are you wasting so much time on escaping quotes when you could just be echoing singles? Why are you using WHILE to do FOR's job... if you want two per TR, why are you looping the same one inside the loop?!?

    ... and yeah, as yelbom implied your formatting is illegible rubbish. Even assuming the cut/paste or the goof assed 'php' bbcode stripped the carriage returns, if you need to indent with that many spaces there is something horrifically wrong with your code.

    I would gut that down to:
    
    <div id="images">
    <?php
    	while($rows=mysql_fetch_array($result)) echo '
    		<img src="upload/',$rows[company_logo],'" width="100" height="100" />';
    	}
    <?php>
    <!-- #images --></div>
    Code (markup):
    ... and then use CSS to format them as appropriate. If you REALLY want to use a table for formatting (boo, hiss)... then it would be something more like this:

    
    <table id="images">
    <?php
    	$count=0;
    	while($rows=mysql_fetch_array($result)) {
    		$link=;
    		if ($count % 1 == 0) echo '
    			<tr>';
    		echo '
    				<td><img src="upload/',$rows[company_logo],'" width="100" height="100" /></td>';
    		$count++;
    		if ($count % 1 == 0) echo '
    			</tr>';
    	}
    	if ($count % 1 == 1) echo '
    				<td></td>
    			</tr>';
    <?php>
    </table>
    
    Code (markup):
    Though really you have no legitimate reason to be doing that since it's pissing all over semantics.

    Either way everything else you're doing in the code looks like it belongs in the CSS... and you REALLY should get some alt text on those images too.
     
    deathshadow, Jan 1, 2013 IP
  4. nxgweb

    nxgweb Member

    Messages:
    9
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    46
    #4
    You can easily done this with DIV and CSS. Use float:left; style.
     
    nxgweb, Jan 1, 2013 IP
  5. ameerulislam43

    ameerulislam43 Active Member

    Messages:
    27
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    56
    #5
    Bro you have raised pretty interesting points. I really appreciate that. The other day I asked what is the difference between while and for loop. No one seemed to have a good answer. Most of them where saying they are the same just different way of formatting and is a personal preference. But here you were saying that why I was using 'while' for 'for' job. Can you tell me why you said that? That's really making me curious.
    Thanks Again!


     
    ameerulislam43, Jan 11, 2013 IP
  6. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #6
    A while loop keeps looping while the initial condition is true. A for loop loops for a specific number of times. Which one you use depends on which action you want. (It's most certainly not a matter of personal preference.)
     
    Rukbat, Jan 11, 2013 IP
  7. HostPlanz

    HostPlanz Well-Known Member

    Messages:
    449
    Likes Received:
    34
    Best Answers:
    4
    Trophy Points:
    130
    #7
    Deathshadow, do you always have to b so arrogant. Ppl come here to learn
    ... do you really expect them to have it all together, or does acting that way make you feel better about yourself?
     
    HostPlanz, Jan 11, 2013 IP
    ryan_uk likes this.
  8. edduvs

    edduvs Well-Known Member

    Messages:
    394
    Likes Received:
    31
    Best Answers:
    3
    Trophy Points:
    160
    #8
    The answer to your initial question (i keep getting images displayed twice) is quite simple if you read the mysql_fetch_array function (which by the way is deprecated since php 5.5 and will be erased, I suggest you start using MySQLi).

    OnTopic: mysql_fetch_array($foo) results an array with both associative and non-associative indexes. Which means, you will get the same result twice in an array, for example : array('image1' => '/images/1.jpg', '0' => '/images/1.jpg); That is the reason why you are getting images twice looping the array.

    A very simple and logical fix is using mysql_fetch_assoc($foo) which will return only the associative array instead both of the indexes. For example: array('image1' => '/images/1.jpg');
    And you can use while, for, repeat or whatever repetitive structure that has the conditional statement either at the beginning or at the end.

    Thats it for the php, regarding the way you are programming, I admit it's kind of silly but, I sugges yout search for php coding optimisation tricks, or google for how to smart code in PHP. I'm not asking you to code with Oriented Objects, but you need to make your code easier to understand over a year when you take another look at it, and immediately understand what you wanted to accomplish using that code a year ago.

    PS. Take a look at "$rows[company_logo]" , PHP will consider company_logo as being an constant since it is not encapsed into any kind of quotes so It will probably return $rows[0]'s value.

    Best regards.
     
    edduvs, Jan 11, 2013 IP
    ryan_uk likes this.
  9. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #9
    Sorry but no, that's NOT what was happening. Notice the second nested while -- It's literally there JUST to loop back once displaying it twice.

    If you add formatting, it becomes VERY apparent why it's outputting the same IMG twice... once in each TD side by side.

    
    while($rows=mysql_fetch_array($result)) {
    	$link=$rows[company_logo];
    	$count=0;
    	echo "<tr>";
    	while($count<=1) {
    		echo "<td><img src=\"upload/$link\" width=\"100px\" height=\"100px\"/></td>";
    		$count++;
    	}
    	echo "</tr>";
    }
    Code (markup):
    That's all the inner loop seems to be there to do -- output the same image more than once... which is why it shouldn't be there at all.
     
    deathshadow, Jan 11, 2013 IP
  10. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #10
    Sorry, it's 2013, I'm getting a bit tired of seeing people STILL sleazing out HTML 3.2 like it was 1997 -- then either slapping a tranny on it or giving it 5's lip-service. Be it because of half-assed web rot like W3Schools, or book writers who change four pages, and slap "HTML 5" on the title without actually pulling their head out of 1998's backside, to the sleazeball 'jquery for everything' re-re's who are taking perfectly good websites and making them less useful than they were a decade ago!

    We need someone like Gordon Ramsey, Simon Cowell or Charlie Frattini to basically give the entire industry an enema -- especially with people being DUMB ENOUGH to think there are ANY improvements offered by that steaming pile of manure known as HTML 5, PHP developers who think they don't actually need to know HTML, and "artists" pretending to be "designers" when they don't know enough about HTML, CSS, fonts for screen, screen media targets, or accessibility to be opening their mouths on the subject.

    I swear, most of the sleazy, lazy, halfwits that have entered the industry the past four years make the 1970's "Charge by the K-Loc" crowd look like George Washington after he chopped down the cherry tree.

    So if I can take the time to try and point someone who needs help AWAY from these outdated, sleazeball half-assed practices, I do so... with as strong a language as I can get away with to drill the point home. To paraphrase Patton it may not sound nice to a bunch of little old ladies at a tea party...

    Or better, "The Wolf"'s If I'm curt with you it's because time is a factor. I think fast, I talk fast and I need you guys to act fast if you wanna get out of this. So, pretty please... with sugar on top. Clean the ****** car.
     
    Last edited: Jan 11, 2013
    deathshadow, Jan 11, 2013 IP
  11. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #11
    Boy, do I hear you. People hire "web developers" who don't know the difference between a for loop and a while loop. I think the vast majority of people posting on "webmaster" forums think that anyone can just sit down with the "right" program and create websites (and make a lot of money).

    It's indicative of what's going on in all industries these days. "Learn" is a dirty word, and giving people value for their money is an old-fashioned idea. Today it's just how much money can you get for how little effort. And the suckers refuse to learn enough to learn how badly they're being robbed.
     
    Rukbat, Jan 12, 2013 IP
  12. ameerulislam43

    ameerulislam43 Active Member

    Messages:
    27
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    56
    #12
    If we put while loop in this way..

    
    $a=0;
    while(5>$a)
    {
        echo $a;
         $a++;
    
    }
    
    
    PHP:
    Is this while loop can be called equal to 'for' loop now?

    Thanks
     
    ameerulislam43, Jan 14, 2013 IP
  13. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #13
    
    while (condition) {
    code
    }
    
    Code (markup):
    is a while loop. It doesn't matter whether you can predetermine the number of loops or not.
     
    Rukbat, Jan 15, 2013 IP
  14. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #14
    It could be considered equivalent -- as could this:

    
    $a=0;
    while ($a < 5) echo ++$a;
    
    Code (markup):
    or this:
    
    $a=0;
    do { echo $a } while ($a++<5);
    
    Code (markup):
    But while can do easier things than just looping a fixed number of iterations. In theory 'back in the day' the two routines would have resulted in wildly different code -- optimizing multipass compilers often reduce them to the same thing, but with PHP having by comparison a rather... dumb parser and being an interpreted language, it can be a bit literal.

    Quite often you have to just sit there and think "Which of these is going to do the least work" -- and sometimes you just have to experiment to figure which one best fits the task at hand. For fixed loops a lot of developers just favor 'for' because it just puts it all in one place so you can see the starting value, ending condition and operator... with while it can end up a bit spread out. That's a hefty part of why 'while' is preferred for boolean operations, not counts.

    Though if we wanted 'optimal' under the hood code for counts, the way EVERY high level language programmer does it is back-assward... since we should actually be starting with a value and decrementing it until zero, so the processor can use the sign, zero, overflow (or whatever a specific processor family has) flags to indicate end of loop...

    
    mov  ecx,5
    @loop:
    ; put code to send value in ecx to stdout here
    loop @loop
    
    Code (markup):
    ... but dimes to dollars PHP isn't smart enough to take such things into consideration.
     
    deathshadow, Jan 15, 2013 IP