I'm trying to save into file a mysql SELECT query as follows:
$result = mysqli_query($db,$sql);
$out = fopen('tmp/csv.csv', 'w');
while ($row = $result -> fetch_row()) {
fputcsv($out,$row);
}
fclose($out);
after save I need to publish on a page as follows :
while ($row = mysqli_fetch_assoc($result)) {
//embed html code
}
The problem is that anytime I run $result->fetch_row(), a record of data is lost. I need to be able to run fetch_object at least 2 times within my code and preserve the data. I thought cloning would be a good solution for this, but it isn't.
Any hints, other that doing 2 query on the sql database ?
If you need to re-use the data, load it into an array - or do all the logic in the same loop.
So for example,
$data = []:
$result = $mysqli->query("...");
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
$out = fopen('tmp/csv.csv', 'w');
foreach ($data as $row) {
fputcsv($out, $row);
}
fclose($out);
// ...
foreach ($data as $row) {
//embed html code
}
Or do it all in the same loop (this may not always be possible, so if it isn't, go with the option above).
$result = mysqli_query($db, $sql);
$out = fopen('tmp/csv.csv', 'w');
while ($row = $result->fetch_row()) {
fputcsv($out,$row);
// embed HTML
}
fclose($out);
If you have mysqlind
installed as part of your PHP MySQL infrastructure, Use a fetch_all()
to get all the results into an array. You can then use that array as many times as you like.
$result = mysqli_query($db,$sql);
$all_results = $result->fetch_all();
$out = fopen('tmp/csv.csv', 'w');
foreach ( $all_results as $row){
fputcsv($out,$row);
}
fclose($out);
// now to reuse the array for your HTML output
foreach ($all_results as $row) {
//embed html code
}
Then you can reuse $all_results
If you dont have mysqlind
then write a simple loop to load an array manually with all the results from the resultset
$result = mysqli_query($db,$sql);
$all_results = [];
while ($row = $result -> fetch_assoc()) {
$all_results[] = $row;
}
$out = fopen('tmp/csv.csv', 'w');
foreach ( $all_results as $row){
fputcsv($out,$row);
}
fclose($out);
// now to reuse the array for your HTML output
foreach ($all_results as $row) {
//embed html code
}
I believe another solution that could work is to use mysqli_data_seek
.
The mysqli_result object is a pointer that moves through the data with each call of fetch_row(), but you can move the pointer back to the beginning by calling
mysqli_data_seek($result, 0);
And now the result is "reset", as it were, and you can use it again.
Learn more here: