Thelambofgoat
Thelambofgoat

Reputation: 609

Break query data into several files

I want to get table from database and then break output data by files (50 entries in each file): list01.txt, list02.txt... But somehow I got stacked at the question how to break data more effectively.

if ( $result = $mysqli->query($query) ) {

    icount = 0;
    while ( $row = mysqli_fetch_array($result) ) {
        if ( icount % 50 == 0 ) {
            $snum = int( icount / 50 );
            $filename = 'scripts/spisok'.$snum.'.txt';
            $handle = fopen( $filename, 'w' );
        }
        fwrite( $filename, $row['uname'].';'.$row['email'].'<br />' );
        icount++;
    }

    echo 'ok';
    $result->free();

}

Can I just break $result into 50-entry arrays first and then write them all? Sorry, im novice to PHP

Upvotes: 0

Views: 86

Answers (2)

bystwn22
bystwn22

Reputation: 1794

You can also use array_chunk

<?php
  if ( $result = $mysqli->query( $query ) ) {
    $data = array();
    while( $row = mysqli_fetch_array( $result ) ) {
      $data[] = $row['uname'].';'.$row['email'];
    }
    $result->free();

    // divide an array into a desired number of split lists
    $chunks = array_chunk( $data, 50 );
    // loop through chunks
    foreach( $chunks as $index => $chunk ) {
      $file   = 'scripts/spisok'.( $index + 1 ).'.txt';
      $chunk  = implode( "<br />", $chunk );
      file_put_contents( $file, $chunk );
      // or
      /*
      $handle = fopen( $file, 'w' );
      fwrite( $handle, $chunk );
      fclose( $handle );
      */
    }
    unset( $data, $chunks );
  }
?>

Upvotes: 1

RiggsFolly
RiggsFolly

Reputation: 94642

There is nothing particularly wrong with what you are doing except for some syntax errors here and there.

Try this :-

if ( $result = $mysqli->query($query) ) {

    $icount = 0;
    $handle = NULL;
    while ( $row = mysqli_fetch_array($result) ) {
        if ( $icount % 50 == 0 ) {
            if ( $handle !== NULL ) {
               fclose($handle);
            }
            $snum = int( $icount / 50 );
            $filename = 'scripts/spisok'.$snum.'.txt';
            $handle = fopen( $filename, 'w' );
        }
        fwrite( $handle, $row['uname'].';'.$row['email'].'<br />' );
        $icount++;
    }

    fclose($handle);
    echo 'ok';
    $result->free();

}

Upvotes: 0

Related Questions