views:

20

answers:

3

are there any way to duplicate the resources produced by functions such as mysql_query?

it may sound dumb but i wanted to reuse such resources so that i won't retype the mysql_query() again and again just to use have a resource..like for example

$rsrc = mysql_query('SELECT * FROM `table` LIMIT 0,1');
$rows = mysql_fetch_array($rsrc);
print_r($rows);

when you fetch a resource, it's value will disappear (that's what i think) what i wanted to do is to reUse it again.i even tried..

$rsrc = mysql_query('SELECT * FROM `table` LIMIT 0,1');
$rsrc_copy = $rsrc;
A: 

You don't need to reuse the resource. You can reuse the rows.

tandu
A: 

Put the result in an array and use it as many times as you like.

$results = array();
$qry = mysql_query("SELECT * from ...");
while($row = mysql_fetch_array($qry)){
  $results[] = $row;
}

// use the $results array
Sabeen Malik
i already have those functions..get_rows and get_cell the problem is they both use the param $resource
kapitanluffy
in that case, i think Pekka's answer should suffice.
Sabeen Malik
@kapitanluffy it doesn't matter that they use `$resource`. You will be able to use `$results` afterwards, you won't need `$resource` any more
Pekka
+1  A: 

when you fetch a resource, it's value will disappear (that's what i think) what i wanted to do is to reUse it again.i even tried..

What you are experiencing is not the value disappearing, but the result's internal data pointer moving one row ahead.

It is theoretically possible to move the internal data pointer around using mysql_data_seek(), but it is rarely practical to do so. I've never seen this used in a real world application. Rather re-use the result you fetched, e.g. by storing the rows in an array.

Pekka
the problem is i have these functions..get_rows($resource) and get_cell($resource) that's why im thinking of reusing them xD
kapitanluffy
@kapitan then maybe you need to rewrite those functions. It's not a good idea to meddle around with resources
Pekka
yup i shud rewrite mysql::select() then it would return an array already instead of a resource..or maybe i could make returning a resource as an optional parameter thanks :)
kapitanluffy
@kapitan querying resources has the advantage that you can pull through huge amounts of data without reaching the memory limit. (If you fetch a million records into an array, it will cost your script that amount of memory. Fetching them from a mySQL result set one by one won't.) But usually, you use a result only in one direction, fetching one record after another. It shouldn't be necessary to "rewind"
Pekka