Newbie Coder
Newbie Coder

Reputation: 10942

How to get the mysql column/field value in PHP without specifying each field?

I am a beginner to PHP and MySQL so please bear with me...

I am trying to get the field values of a mysql table using a for loop. I know to how to get it by using mysql_fetch_array but the thing is I have to specify each field. I want to do it by just getting the number of fields and use a loop to get the values. I also tried mysql_fetch_field but I can't find any functions that return the value.

Here is the list of mysql_fetch_field return values:

I also tried reading about mysql_result but it seems that you have to specify the field.

mysql_result [field]

The name or offset of the field being retrieved.

It can be the field's offset, the field's name, or the field's table dot field name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name. If undefined, the first field is retrieved.


Here is my code fragment:

<table> 
 <tr>
  <?php
   for ($i = 0; $i < mysql_num_fields($result); ++$i) echo  "<th>" . mysql_field_name($result, $i) . "</th>"  ;
  ?>
 </tr>
 <?php 
  for ($i = 0; $i < mysql_num_rows($result); ++$i) {  
   echo "<tr>";
   for ($j = 0; $j < mysql_num_fields($result); ++$j) {
    echo "<td>" . // this is where I want to put the function . "</td>";
   }
   echo "</tr>";
  }
 ?>
</table>

Pls help...

Upvotes: 0

Views: 5086

Answers (2)

tlo
tlo

Reputation: 11

this works, but is not so efficient, when working with large result sets, as the full result set is loaded into memory. I'd rather implement an iterator which internally holds the resource return by mysql_query and with every call of next() fetching the next row with mysql_fetch_array and releasing the previous.

Upvotes: 0

Craig White
Craig White

Reputation: 14012

I use this function I made which returns all the results from the SQL into an array.

<?php
function getResultRows($result)
{
    $rows = array();
    while ($row = mysql_fetch_array($result)){
        $rows[] = $row;
    }
    return $rows;
}

$sql = 'SELECT * FROM myTable WHERE 1=1';
$result = mysql_query($sql);
$rows = getResultRows($result);
print_r($rows);
?>

array(
    [0]array(
        [0]id => 0
        [1]name => blah
    )
    [1]array(
        [0]id => 5
        [1]name => test
    )
)

Upvotes: 2

Related Questions