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.. :)
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?
$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?
Please, for the love of the web, don't built an SQL query yourself. Use PDO .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.