Jump to content

[SOLVED] How to detect variable change PostPosted: Sun Feb 08, 2009 2:47 am


markjohnson

Recommended Posts

Is there a way I can detect change in a variable value?

 

This is what I want to achieve:

 

I have a normal select query that lists records with their group_ids... like so...

 

group_id --- number

333

333

333

333

345

345

345

345

 

The number field at the moment is null, and I would like to update that field in each of these records, starting with 1, then 2 and so on... And as soon as group_id changes, from 333 to 345, I would like the numbering to restart.

 

At the moment I have this:

 

<?php
$x=1;
        do {
?>
    <tr>
      <td><?php echo $row_rsOptionGroups['id']; ?></td>
      <td><?php echo $row_rsOptionGroups['group_id']; ?></td>
      <td><?php echo $row_rsOptionGroups['display_value']; ?></td>
      <td><?
        $g_id=$row_rsOptionGroups['group_id'];
        $y=$g_id;
        if ($y != $row_rsOptionGroups['group_id']) {
            $x=1;
            $g_id=$row_rsOptionGroups['group_id'];
        }
      echo $x;
      $x=$x+1;
      ?></td>
      <td><?php echo $row_rsOptionGroups['option_price']; ?></td>
    </tr>
    <?php
    } while ($row_rsOptionGroups = mysql_fetch_assoc($rsOptionGroups)); 
?>

 

And it obviously doesn't work.

 

Is there a way I can do:

 

If ($row_rsOptionGroups['group_id'] changes from what it previously was) {
   $x=1;
}

 

Many Thanks

Here is the concept:

 

// generate example list of numbers...
for ($x = 0; $x < 50; $x++) {
   $info[] = rand(1,10);
} // end for $x
sort($info);

foreach($info as $num) {
   $count = ($prevnum != $num)? 1 : ++$count;
   $prevnum = $num;
} // end foreach 

Here is an example...

 

Seeing you didn't show me your REAL TABLE scheme you will have to change my code to to reflect your table setup...

 



<?php

mysql_connect ( 'localhost', 'user', 'pass' );

mysql_select_db ( 'database' );

$w = mysql_query ( "SELECT id, group_id FROM your_table WHERE option_number IS NULL OR option_number = '' ORDER BY group_id;" );

if ( mysql_num_rows ( $w ) > 0 )
{
$out = array ();

$i = 0;

$n = 0;

while ( $r = mysql_fetch_assoc ( $w ) )
{
	if ( $n != $r['group_id'] )
	{
		$i = 1;
		$n = $r['group_id'];
	}

	$out[] = array ( $r['id'], $i );

	$i++;
}

while ( ! empty ( $out ) )
{
	$data = array_shift ( $out );

	mysql_query ( "UPDATE your_table SET option_number = '" . $data[1] . "' WHERE id = '" . $data[0] . "';" );

}
}

?>


Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.