views:

79

answers:

3

I have a mysql_query result that I am looping through multiple times in different parts of code, each time using a mysql_data_seek( $result, 0 ) to reset to the beginning of the result.

I am using mysql_fetch_array on those results, and would like to remove a few specific rows from the $result. Basically the equivalent to unset( $result[$row] ) if it was a normal array. Is there any way to do this?

Sample code:

$result = mysql_query( $sql );
$num_rows = mysql_num_rows( $result );
if( $num_rows ){
    for( $a=0; $a < $num_rows; $a++ ){
    $row = mysql_fetch_array( $result );
    if( my_check_function( $row['test'] ){
       // do stuff
    } else {
      // remove this row from $result
    }
  }
}
mysql_data_seek( $result, 0 );

I know I can simply do unset( $row[$a] ) to remove that specific row, but after the data seek and I loop through the results next time I end up with the same original result rows.

Any help would be appreciated. ps - Not sure why the _'s were removed in my top text and changed to italics, I tried to fix it but it ended up being bold.. :)

+5  A: 

The best option is to re-write your queries so you don't have to remove any records after running a query against your database. That, or insert your records into another array, and merely skip over the ones you don't want.

$survivors = array();

while ($row = mysql_fetch_array($result)) { // while we have records
  if (do_something($row))                   // if this is a good record
    $survivors[] = $row;                    // save it for later
}

print_r($survivors);                        // who survived the cut?
Jonathan Sampson
Ok, thanks, that is what I ended up doing. I was curious if there was a way to directly change the mysql_query result itself, guess not :)
Rob
Rob, the result is not an array. That's why you pass it through mysql_fetch_array (or _fetch_object) to get your values. For this reason, you have to deal with each row 1-by-1.
Jonathan Sampson
+2  A: 
$result = mysql_query( $sql );
$new_rows = mysql_num_rows( $result );
$new_array = array();
if( $num_rows ){
    for( $a=0; $a < $num_rows; $a++ ){
    $row = mysql_fetch_array( $result );
    if( my_check_function( $row['test'] ){
                        // do stuff
         // populate new array with only validated data
         $new_array[$a] = $row;
    } else {
                // remove this row from $result
            // do not remove anything. 
    }
  }
}

PS. Are you sure you can't sort out unnecessary rows within your sql query?

Ilya Biryukov
A: 

Please, for the love of the web, don't built an SQL query yourself. Use PDO.

Paul Tarjan