Jump to content

Can you parse a variable?


coupe-r

Recommended Posts

I am inside a while loop.

 

while($row = mysql_fetch_array($result))

{

      echo '<td width="25%" align="center">' . $row['prod_name'] . '</td>'

}

 

I want a table with 4 columns across, and the number of rows based on how many products I have.  If I have 4 products, then 1 row, if I have 8 products then 2 rows, etc.

 

I cannot figure out how to have the var $row['prod_name'] if there are more than 1 row.  All values are spaced out in 1 single row.

Link to comment
https://forums.phpfreaks.com/topic/155296-can-you-parse-a-variable/
Share on other sites

Im querying all products inside the DB and then the while loop should loop through all products queried and display them from left to right, like this.

 

1  2    3    4

 

5  6    7    8

 

Right now, they display

 

1  2  3  4  5  6  7  8  ---->

 

edit: this won't work. need to change it.

 

Edit again:

 

Okay, I didn't test it, but this should work:

 


$row = mysql_fetch_array( $result, MYSQL_ASSOC );

for ($i = 0; $i >= 0;  $i++)

{

if ( $i > 1 )
$g = $i * 4;

echo '
<tr>
<td width="25%" align="center">' . $row[$i+$g]['prod_name'] . '</td>
<td width="25%" align="center">' . $row[$i+1+$g]['prod_name'] . '</td>
<td width="25%" align="center">' . $row[$i+2+$g]['prod_name'] . '</td>
<td width="25%" align="center">' . $row[$i+3+$g]['prod_name'] . '</td>
</tr>';

}

 

not sure why "&#160;" is showing up in my for loop. I think you get what I mean though:

 

for ( $i = 0; $i >= 0; $i++ )

Notice: Undefined offset: 0 in D:\Apache\htdocs\producttest.php on line 36

 

Notice: Undefined offset: 1 in D:\Apache\htdocs\producttest.php on line 37

 

Notice: Undefined offset: 2 in D:\Apache\htdocs\producttest.php on line 38

 

Notice: Undefined offset: 3 in D:\Apache\htdocs\producttest.php on line 39

 

 

 

Can't edit my post again... but you need to change this:

if ( $i > 1 )
$g = $i * 4;

 

to this:

 

if ( $i > 0 )
$g = $i * 4;

 

Because 0 will be the general starting point for the array, it needs to be greater than the first, rather than the "actual" first, which is 1.

 

edit: it's late, and i keep confusing myself, so I'm going to stop now... hope this works for you.

No.

 

Use the mod operator.  It will be similar to this, but this generates extra markup that is escaping me how to easily stop it from doing so.

$i = 0;
while($row = mysql_fetch_array($result))
{
  if( (($i % 4) == 0) && ($i != 0) ){
    echo '</tr><tr>';//you need to fix this so that it doesn't always add the <tr>
  }
      echo '<td width="25%" align="center">' . $row['prod_name'] . '</td>'
  $i++;
}

At least I think it adds extra markup...?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.