-1

I want to take some integers from the apriori_main table and store them into a text file as comma separated values. For each iteration I use file_put_contents to write data on the next line. Using fwrite gives the same result.

The output I want in the text file is:

1,2,3,4

But the output I'm getting is:

1  
,2  
,3  
,4  

Here is the code snippet:

$y="";
$stmt='SELECT category FROM apriori_main where id='.$id.''; 
$nRows = $conn->query('select count(category) from apriori_main where id='.$id.'')->fetchColumn(); 
echo $nRows;

$file = "/opt/lampp/htdocs/ghi.txt";
$f = fopen($file, 'a+'); // Open in write mode
$count=1;

foreach($conn->query($stmt) as $row)
{ 
    if($count!=$nRows) 
    {
        $user = $row['category']."\n"; 
        $y=$user; $y=$y.",";
        $str=$y; echo $y;
        $count=$count+1;
    }
    else
    { 
        $user = $row['category']."\n";
        $y=$user; $str=$y; echo $y; 
    }
    file_put_contents($file, $str, FILE_APPEND);
}
fclose($f);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87

2 Answers2

0

This is all that is needed:

$stmt = 'SELECT category FROM apriori_main where id='.$id.''; 
$file = "/opt/lampp/htdocs/ghi.txt";

foreach($conn->query($stmt) as $row)
{ 
    $str[] = $row['category'];
}
file_put_contents($file, implode(',', $str));
// only use FILE_APPEND if needed for the next time to append
  • Loop through query result rows
  • Append category to an array
  • Implode array elements with a comma , and write to the file

So in short, you:

  1. Don't need to query for the count
  2. Don't need to open the file
  3. Don't use \n that's a newline
  4. Don't need to add the comma , in the loop
  5. Don't write each loop iteration
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
-1

I don't know what else you're doing with these values, but you seem to have a ton of unnecessary variable declaring.

I think you can effectively break all of this

 $file = "/opt/lampp/htdocs/ghi.txt";
      $f = fopen($file, 'a+'); // Open in write mode
        $count=1;


      foreach($conn->query($stmt) as $row)
      { 
         if($count!=$nRows) 
         {
            $user = $row['category']."\n"; 
            $y=$user; $y=$y.",";
            $str=$y; echo $y;
            $count=$count+1;
         }
         else
         { 
            $user = $row['category']."\n";
            $y=$user; $str=$y; echo $y; 
         }
         file_put_contents($file, $str, FILE_APPEND);
     }
         fclose($f);

Down to this (with only one file operation at the end)

$file = "/opt/lampp/htdocs/ghi.txt";

foreach($conn->query($stmt) as $row)
{ 
    $y[] = $row['category']; 
}
//output to screen
echo implode("<br>", $y);
//output to file
file_put_contents($file,implode(",", $y));
Dano
  • 169
  • 9