Help - Search - Members - Calendar
Full Version: PHP FOR loops and MySQL table rows
HTMLHelp Forums > Programming > Databases
Christian J
Just for practice I'm trying to loop through a MySQL table, comparing each row with the rest. With (multidimensional) arrays I might do this with nested FOR loops --doesn't that work with MySQL tables? Haven't found much on the subject, but http://www.php.net/manual/en/function.mysq...-rows.php#47520 says that "there seems no way of getting the CURRENT row number that's under iteration in a typical loop". If true, this seems very limiting... unsure.gif
Christian J
Seems you can at least make your own PHP array:

CODE
$query = mysql_query("SELECT * FROM foo");

// make PHP array
$i=0;
while($item = mysql_fetch_array($query))
{
    $arr[$i]=$item;
    $i++;
}

// print PHP array
echo '<pre>';
for($j=0; $j<count($arr); $j++)
{
    echo "row $j: ";
    for($n=0; $n<count($arr[$j]); $n++)
    {
        echo $arr[$j][$n]." ";
    }
    echo "\n";
}
echo '</pre>';
Christian J
For SQLite PHP offers sqlite_array_query(), which returns an array --not a resource-- so you can apply FOR loops right away. Strange that such a function doesn't exist for MySQL.
Brian Chandler
QUOTE(Christian J @ Jun 29 2010, 07:14 AM) *

For SQLite PHP offers sqlite_array_query(), which returns an array --not a resource-- so you can apply FOR loops right away. Strange that such a function doesn't exist for MySQL.


Well, then write your own function. I don't quite understand the problem here: generally you get rows from mysql using a while loop, and if you want to count the row number, for example to add a heading every ten rows, then it's something like:

CODE

$row = 0;
while ($row = mysql_fetch_array(...))
{  if ($row%10 == 0)
      <... show header line...>

  ... show stuff ...

   $row++;
}


The thing that did seem to be missing from mysql is "Get rows 11-20 of query", which is what you need for output paging. But you can just write your own function to do what you need. (This is the difference between programming, where things get easier as you go along, and point-and-grunt manual stuff, like using Whirred or CSS, where they get more and more tangled up.)
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2024 Invision Power Services, Inc.