Andrew
Andrew

Reputation: 233

how to display result of query

After query I try to display data. I can receive only data from 'field_1[]'. From 'field_2[]' and from 'field[]' no. How to fix it?

if (!$result) {    
die("Query to show fields from table failed");
}

$fields_num = mysql_num_rows($result);

//------------------------------------------------------------------    
for($i_1=0; $i_1<$fields_num; $i_1++)
{    
$field_1 = mysql_fetch_assoc($result);    
echo "<td>a".$field_1['index_period_1']."</td>";
}
//------------------------------------------------------------------
//------------------------------------------------------------------

for($i=0; $i<$fields_num; $i++)
{    
$field = mysql_fetch_assoc($result);    
echo "<td>b".$field['index_period']."</td>";
}
//------------------------------------------------------------------
//------------------------------------------------------------------    
for($i_2=0; $i_2<$fields_num; $i_2++)
{    
$field_2 = mysql_fetch_assoc($result);    
echo "<td>c".$field_2['index_period_2']."</td>";
}

edit:----------------------

|------------|period_1  |period_1  |period_1  |
-----------------------------------------------
|period_2    |period    |period    |period    |
-----------------------------------------------
|period_2    |period    |period    |period    |
-----------------------------------------------

Upvotes: 0

Views: 122

Answers (2)

Blender
Blender

Reputation: 298076

You are sort of missing the point of mysql_fetch_assoc() and rows in MySQL:

while ($row = mysql_fetch_assoc($result)) {
  echo $row['index_period'];
  echo $row['index_period_1'];
  echo $row['index_period_2'];
}

You call mysql_fetch_assoc() once per row.


I'm not really sure why you need to loop over your table like this, but I won't interrogate you.

This might fit your needs (I cringe writing this):

$index_period = array();
$index_period_1 = array();
$index_period_2 = array();

while ($row = mysql_fetch_assoc($result)) {
  $index_period[] = $row['index_period'];
  $index_period_1[] = $row['index_period_1'];
  $index_period_2[] = $row['index_period_2'];
}

foreach ($index_period as $value) {
  echo "<td>a" . $value . "</td>";
}

foreach ($index_period_1 as $value) {
  echo "<td>b" . $value . "</td>";
}

foreach ($index_period_2 as $value) {
  echo "<td>c" . $value . "</td>";
}

Upvotes: 1

Nick Rolando
Nick Rolando

Reputation: 26157

Once you finish your first for loop, you have iterated through the entire result set. So when you enter your next for loop, there is nothing left to iterate and mysql_fetch_assoc() returns false. If you want to reset the internal data pointer, you can call

mysql_data_seek($result, 0);

This will enable you to re-iterate through the result set in your next for loop.

Upvotes: 0

Related Questions