I'm having trouble using the mysqli_free_result()
function. I am nesting queries and it seems when I free the results it stops the initial query from running its loop with the while()
function. Am I using the mysqli_free_result()
improperly? If I change the name of the 2nd query from $results
to $results2
it works fine. Seems there is an issue with the variables over writting, which is where I thought mysqli_free_result()
would help but apparently not.
Here is a sample code similar to what I am trying to do.
<?php
// 1st query
$query = '';
// Run the 1st query
if( $results = mysqli_query( $db_connect, $query ) ) {
while( $result = mysqli_fetch_assoc( $results ) ) {
// 2nd query
$query = '';
// Run the 2nd query
if( $results = mysqli_query( $db_connect, $query ) ) {
while( $result = mysqli_fetch_assoc( $results ) ) {
}
mysqli_free_result( $results );
}
}
mysqli_free_result( $results );
}
?>
Try using a different variable name for your inner query. Currently you are overwriting the $results
on every run of the outer while
loop.
<?php
// 1st query
$query = '';
// Run the 1st query
if( $results = mysqli_query( $db_connect, $query ) ) {
while( $result = mysqli_fetch_assoc( $results ) ) {
// 2nd query
$query = '';
// Run the 2nd query
if( $results_2 = mysqli_query( $db_connect, $query ) ) {
while( $result_2 = mysqli_fetch_assoc( $results_2 ) ) {
}
mysqli_free_result( $results_2 );
}
}
mysqli_free_result( $results );
}
?>
Update: As already pointed out on other comments and answers, mysqli_stmt_free_result
frees the memory for the supplied statement handle as stated in the docs http://www.php.net/manual/en/mysqli-stmt.free-result.php. As @andrewsi points out, the issue is variable scoping issue.
Free results frees up the handle, the results handle isn't a stack, you need to name your results handle's differently, unless you want them to overwrite.
"Frees the memory associated with the result." - php docs