Page 1 of 1

Iterate All Rows ?

Posted: Wed May 11, 2005 5:10 pm
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.

Posted: Thu May 12, 2005 1:33 am
by anjanesh
Using MySQL statements alone or using PHP code too ?
Using PHP code is simple - use the mysql functions.

Posted: Fri May 13, 2005 10:42 am
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.

Posted: Fri May 13, 2005 2:38 pm
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());
}