Php free result mysqli

mysql_free_result

Данное расширение устарело, начиная с версии PHP 5.5.0, и будет удалено в будущем. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API и соответствующий FAQ для получения более подробной информации. Альтернативы для данной функции:

Описание

mysql_free_result() высвободит всю память, занимаемую результатом, на который ссылается переданный дескриптор result .

mysql_free_result() нуждается в вызове только в том случае, если вы всерьёз обеспокоены тем, сколько памяти используют ваши запросы к БД, возвращающие большое количество данных. Вся память, используемая для хранения этих данных автоматически очистится в конце работы скрипта.

Список параметров

Обрабатываемый результат запроса. Этот результат может быть получен с помощью функции mysql_query() .

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Если в качестве параметра result передан не ресурс, то будет вызвана ошибка уровня E_WARNING. Стоит также заметить, что mysql_query() возвращает resource только для запросов SELECT, SHOW, EXPLAIN и DESCRIBE.

Примеры

Пример #1 Пример использования mysql_free_result()

$result = mysql_query ( «SELECT id,email FROM people WHERE » );
if (! $result ) echo ‘Не удалось выполнить запрос: ‘ . mysql_error ();
exit;
>
/* Используем результат, подразумевая, что после этого он нам больше не нужен */
$row = mysql_fetch_assoc ( $result );

/* Теперь освобождаем результат и продолжаем дальнейшую работу над нашим скриптом */
mysql_free_result ( $result );

echo $row [ ‘id’ ];
echo $row [ ’email’ ];
?>

Примечания

Замечание:

Для обратной совместимости может быть использован следующий устаревший псевдоним: mysql_freeresult()

Смотрите также

Источник

mysqli_free_result

You may have a stored procedure in your query. A procedure can return more than one result set, and it will always return one extra empty result set that carries some meta information on the procedure call itself, especially error information. ( source: https://bugs.mysql.com/bug.php?id=71044 )

While calling single procedures, with one SELECT in them, using mysqli->query(«CALL `stored_procedure`();»), I had to do the following to make it work between two calls:

$result -> free ();
$mysqli -> next_result ();
?>

It has no negative impact if you are not calling a stored procedure.

We should free the mysql results using mysqli_free_result respectively or else this will consume your server RAM resource.

This is demonstrated as below

$link = mysqli_connect ( ‘Hostname’ , ‘Username’ , ‘Password’ , ‘Database’ );

echo ‘
Memory Usage Before Query = ‘ . memory_get_usage ( false ); // 449464 bytes

$resultResource = mysqli_query ( $link , ‘SELECT * FROM test’ );

echo ‘
Memory Usage after Query = ‘ . memory_get_usage ( false ); // 466528 bytes

$result = array();
while ( $result [] = mysqli_fetch_assoc ( $resultResource )) <>

echo ‘

Memory Usage Before Free Result = ‘ . memory_get_usage ( false ); // 474208 bytes

echo ‘
Memory Usage After Free Result = ‘ . memory_get_usage ( false ); // 457336 bytes

Memory Usage Before Query = 449464
Memory Usage after Query = 466528

Memory Usage Before Free Result = 474208
Memory Usage After Free Result = 457336

So, One can observer there is memory usage after the query is executed. The results are returned by DB server to the web server instantaniously once the query execution is over. The results present on web server are then processed for fetching from the resource link on web server.

Also this is observed that there is lesser memory usage after using mysqli_free_result because the resources stored on web server for respective query are freed by providing respective resource link.

If you are getting this error:
Internal SQL Bug: 2014, Commands out of sync; you can’t run this command now

Then you never called mysqli_result::free(), mysqli_result::free_result(), mysqli_result::close(), or mysqli_free_result() in your script, and must call it before executing another stored procedure.

Freeing the memory associated with a result means that the references returned by mysqli_fetch_object (or equivalent) are cleared. Thus if you should pass an object pointing to a database row _by reference_, every call of mysqli_free_result will discard the referenced data.

Источник

mysql_free_result

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

Description

mysql_free_result() will free all memory associated with the result identifier result .

mysql_free_result() only needs to be called if you are concerned about how much memory is being used for queries that return large result sets. All associated result memory is automatically freed at the end of the script’s execution.

Parameters

The result resource that is being evaluated. This result comes from a call to mysql_query() .

Return Values

Returns true on success or false on failure.

If a non-resource is used for the result , an error of level E_WARNING will be emitted. It’s worth noting that mysql_query() only returns a resource for SELECT, SHOW, EXPLAIN, and DESCRIBE queries.

Examples

Example #1 A mysql_free_result() example

$result = mysql_query ( «SELECT id,email FROM people WHERE » );
if (! $result ) echo ‘Could not run query: ‘ . mysql_error ();
exit;
>
/* Use the result, assuming we’re done with it afterwards */
$row = mysql_fetch_assoc ( $result );

/* Now we free up the result and continue on with our script */
mysql_free_result ( $result );

echo $row [ ‘id’ ];
echo $row [ ’email’ ];
?>

Notes

Note:

For backward compatibility, the following deprecated alias may be used: mysql_freeresult()

See Also

User Contributed Notes 3 notes

yes this function may increase the memory usage if you use unbuffered querys and if you have not fetched all the data from mysql. in this case the mysql api has a problem: you want to free the result but do not want to close the connection. now mysql will only accept another query if all data has been fetched, so the api now must fetch the rest of the data when calling mysql_free_result().

so only use unbuffered querys if you fetch all the data (and need it).

If you’re seeing warnings like «Warning: Unknown: 6 result set(s) not freed. Use mysql_free_result to free result sets which were requested using mysql_query() in Unknown on line 0» and want to turn them off, set mysql.trace_mode = Off in your php.ini

  • MySQL Functions
    • mysql_​affected_​rows
    • mysql_​client_​encoding
    • mysql_​close
    • mysql_​connect
    • mysql_​create_​db
    • mysql_​data_​seek
    • mysql_​db_​name
    • mysql_​db_​query
    • mysql_​drop_​db
    • mysql_​errno
    • mysql_​error
    • mysql_​escape_​string
    • mysql_​fetch_​array
    • mysql_​fetch_​assoc
    • mysql_​fetch_​field
    • mysql_​fetch_​lengths
    • mysql_​fetch_​object
    • mysql_​fetch_​row
    • mysql_​field_​flags
    • mysql_​field_​len
    • mysql_​field_​name
    • mysql_​field_​seek
    • mysql_​field_​table
    • mysql_​field_​type
    • mysql_​free_​result
    • mysql_​get_​client_​info
    • mysql_​get_​host_​info
    • mysql_​get_​proto_​info
    • mysql_​get_​server_​info
    • mysql_​info
    • mysql_​insert_​id
    • mysql_​list_​dbs
    • mysql_​list_​fields
    • mysql_​list_​processes
    • mysql_​list_​tables
    • mysql_​num_​fields
    • mysql_​num_​rows
    • mysql_​pconnect
    • mysql_​ping
    • mysql_​query
    • mysql_​real_​escape_​string
    • mysql_​result
    • mysql_​select_​db
    • mysql_​set_​charset
    • mysql_​stat
    • mysql_​tablename
    • mysql_​thread_​id
    • mysql_​unbuffered_​query

    Источник

    PHP mysqli_free_result() Function

    A PHP result object (of the class mysqli_result) represents the MySQL result, returned by the SELECT or, DESCRIBE or, EXPLAIN queries.

    The mysqli_free_result() function accepts a result object as a parameter and frees the memory associated with it.

    Syntax

    Parameters

    This is an identifier representing a result object.

    Return Values

    This function doesn’t return any values.

    PHP Version

    This function was first introduced in PHP Version 5 and works works in all the later versions.

    Example

    Following example demonstrates the usage of the mysqli_free_result() function (in procedural style) −

     //Closing the statement mysqli_free_result($res); //Closing the connection mysqli_close($con); ?>

    This will produce following result −

    Table Created. Record Inserted. Contents of the resultset. ID: 1 First_Name: Sikhar Last_Name: Dhawan Place_Of_Birth: Delhi Country: India ID: 2 First_Name: Jonathan Last_Name: Trott Place_Of_Birth: CapeTown Country: SouthAfrica ID: 3 First_Name: Kumara Last_Name: Sangakkara Place_Of_Birth: Matale Country: Srilanka

    If you try to get the contents of the result after freeing it as −

    $con = mysqli_connect("localhost", "root", "password", "mydb"); mysqli_query($con, "CREATE TABLE myplayers(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))"); print("Table Created. \n"); mysqli_query($con, "INSERT INTO myplayers values(1, 'Sikhar', 'Dhawan', 'Delhi', 'India')"); mysqli_query($con, "INSERT INTO myplayers values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')"); mysqli_query($con, "INSERT INTO myplayers values(3, 'Kumara', 'Sangakkara', 'Matale', 'Srilanka')"); print("Record Inserted. \n"); //Retrieving the contents of the table $res = mysqli_query($con, "SELECT * FROM myplayers"); //Closing the statement mysqli_free_result($res); print("Contents of the resultset. \n"); //Contents of the resultset while ($row = mysqli_fetch_row($res)) < print("ID: ".$row[0]."\n"); print("First_Name: ".$row[1]."\n"); print("Last_Name: ".$row[2]."\n"); print("Place_Of_Birth: ".$row[3]."\n"); print("Country: ".$row[4]."\n"); >//Closing the connection mysqli_close($con);

    You will get an error as shown below −

    Table Created. Record Inserted. Contents of the resultset. PHP Warning: mysqli_fetch_row(): Couldn't fetch mysqli_result in E:\PHPExamples\procedure_oriented.php on line 19 Warning: mysqli_fetch_row(): Couldn't fetch mysqli_result in E:\PHPExamples\procedure_oriented.php on line 19

    Example

    In object oriented style the syntax of this function is $result->close(); Following is the example of this function in object oriented style $minus;

     query("CREATE TABLE Test(Name VARCHAR(255), AGE INT)"); $con -> query("insert into Test values('Raju', 25),('Rahman', 30),('Sarmista', 27)"); print("Table Created. \n"); $stmt = $con -> prepare( "SELECT * FROM Test WHERE Name in(?, ?)"); $stmt -> bind_param("ss", $name1, $name2); $name1 = 'Raju'; $name2 = 'Rahman'; //Executing the statement $stmt->execute(); //Retrieving the result $result = $stmt->get_result(); //Number of rows $count = $result->num_rows; print("Number of rows in the result: ".$count); //Closing the result $result->close(); //Closing the statement $stmt->close(); //Closing the connection $con->close(); ?>

    This will produce following result −

    Table Created. Number of rows in the result: 2

    Источник

    Читайте также:  Min key array php
Оцените статью