Why shouldn't you use mysql_fetch_assoc more than 1 time?

Some say you should not use mysql_fetch_assocmore than once, why?

For example: I want to display two tables with users who paid for membership, and the other with users who did not, so instead of querying the database 2 times, I query it once and get a variable $resultwith both types of users, then I run a loop mysql_fetch_assocand see if list['membership'] = 'paid', then the echo ...

The second half I loop the cycle mysql_fetch_assocand see if list['membership'] = 'free', then the echo ...

Which uses less resources, given that I received an equal number of users, registered and unregistered.

+5
source share
4 answers

Think of your query result as a sausage and mysql_fetch_assoc () as a knife that cuts a piece of that sausage. Each time you bring a string, another piece of sausage is trimmed, and this is always a new piece of sausage. You cannot go and cut off the previously cut part because you have already eaten it.

+14
source

Quote Typer85 ( link ):

Please note that the result of the resource that you pass to this function can be considered passed by reference, because the resource is just a pointer to a memory location.

Because of this, you cannot run the result of the resource twice in the same script before returning the pointer back to the starting position.

For instance:

<?php

// Assume We Already Queried Our Database.

// Loop Through Result Set.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

// We looped through the resource result already so the
// the pointer is no longer pointing at any rows.

// If we decide to loop through the same resource result
// again, the function will always return false because it
// will assume there are no more rows.

// So the following code, if executed after the previous code
// segment will not work.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

// Because $queryContent is now equal to FALSE, the loop
// will not be entered.

?>

reset , , :

<?php

// Assume We Already Queried Our Database.

// Loop Through Result Set.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

// Reset Our Pointer.

mysql_data_seek( $queryResult );

// Loop Again.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

?>

, , , 0, mysql_data_seek false, .

, , , mysql_fetch_row, mysql_fetch_assos mysql_fetch_array.

+5

- , mysql_fetch_assoc(), . , mysql_fetch_assoc(), . reset , mysql_fetch_assoc() .

EDIT: mysql_data_seek().

+3

, () (). , mysql. , , ( mysql_fetch ), , , , , PHP . .

0

All Articles