Page 1 of 1

For loop

Posted: Mon Oct 04, 2010 11:43 pm
by vfm
Hi guys,

I've got a three-column CSS-designed layout and in each of those columns I'm trying to put a value from my database. However, I'm very new to this and cant quite figure out the logic for doing it. Below is my code.

Can anyone please tell me how I can get the three IDs in each of the columns and if there are more than three IDs how I do it on a new row etc.

Code: Select all

<div class="col1">
				<!-- Column 1 start -->
				<?php

				$sqlstr = mysql_query("SELECT * FROM `products` WHERE `accessories` = '1'");
				if (mysql_numrows($sqlstr) != 0) {
				while ($row = mysql_fetch_array($sqlstr)) {
				?>
				
<?= row['photo_mid'] ?>"
				
				<!-- Column 1 end -->
			</div>
			<div class="col2">
				<!-- Column 2 start -->
				<h2>This is col 2</h2>
				<?= row['photo_mid'] ?>"
				<!-- Column 2 end -->
			</div>
			<div class="col3">
				<!-- Column 3 start -->
				
				<h2>This is col 3</h2>
<?= row['photo_mid'] ?>"
				
				<!-- Column 3 end -->
			</div>

Re: For loop

Posted: Thu Oct 07, 2010 7:52 pm
by vfm
Anyone? I'm still struggling with this one!

Re: For loop

Posted: Fri Oct 08, 2010 2:01 am
by twinedev
Just guessing on what you are looking for, give this a try:

Code: Select all

define('NUM_COLUMNS',3);

$rsProducts = mysql_query('SELECT * FROM `products` WHERE accessories` = "1"');
if ($rsProducts && mysql_num_rows($rsProducts)>0) {
	$aryProducts = array();
	while ($aryProducts[] = mysql_fetch_assoc($rsProducts));
	mysql_free_result($rsProducts);
}
else {
	$aryProducts = FALSE;
}
unset($rsProducts);

if ($aryProducts) {
	$intProdCount = count($aryProducts); // Used more than onece, hold it
	$intPerCol = ceil($intProdCount/NUM_COLUMNS);
	for($intCol=0;$intCol<NUM_COLUMNS;$intCol++) {
		echo '<div class="col'.($intCol+1).'">';
		for($t=0;$t<$intPerCol;$t++) {
			$intIndex = $t*NUM_COLUMNS+$intCol;
			if ($intIndex <= $intProdCount) {
				echo $aryProducts[$intIndex]['photo_mid'];
			}
		}
		echo '</div>',"\n";
	}
}

Re: For loop

Posted: Fri Oct 08, 2010 2:32 am
by loCode
use echo. <?php echo $row['blah']; ?>

to make your page dynamic, use echo in a loop.

Re: For loop

Posted: Mon Oct 11, 2010 11:39 pm
by vfm
Hi twindev,

THanks that worked pretty well - however the only thing it doesn't do is go to a new line if there are more than three items. Would there be much modification to your code to include this functionality?

Thanks in advance.

Re: For loop

Posted: Thu Oct 14, 2010 6:36 pm
by vfm
Does anyone know how I can modify the above code so that if there are more than three items it should break to a new line?

Re: For loop

Posted: Tue Oct 19, 2010 8:31 pm
by vfm
Is anyone please able to assist me with this?