Iterate All Rows ?

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
Death
Forum Newbie
Posts: 17
Joined: Tue Apr 19, 2005 11:52 am

Iterate All Rows ?

Post by Death »

Hi guys,

How do I loop through every row in my table ?

I basically want to get the data in the row, modify it, then store it; for every row.

Thanks.
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Post by anjanesh »

Using MySQL statements alone or using PHP code too ?
Using PHP code is simple - use the mysql functions.
Death
Forum Newbie
Posts: 17
Joined: Tue Apr 19, 2005 11:52 am

Post by Death »

Hi,

Using PHP also. I basically want to go through each row, get the data from some fields, manipulate that data (in PHP), then store some results in the same row.

Thanks.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

OK just use SELECT without a WHERE clause to get every row. Then loop over what you take out and run the queries from within the loop.

It may be the case that you don't even need to use much PHP to update the data.... it depends what you're updating it with since UPDATE can do all rows too if you want it too.

Code: Select all

$query = "SELECT `pri_key`, `field_name` FROM `table`";
$result = mysql_query($query) or die (mysql_error());
$num_rows = mysql_num_rows($result);

for($i=0; $i<$num_rows; $i++) {
    $field_value = mysql_result($result, $i, 'field_name');
    $id = mysql_result($result, $i, 'pri_key');
    $new_value = 'new_...whatever junk here'. $field_value; //for example
    $update_query = "UPDATE `table` SET `field_name`='$new_value' WHERE `pri_key`='$id'";
    mysql_query($update_query) or die (mysql_error());
}
Post Reply