简体   繁体   中英

Writing SQL query results to a text file

I am attempting to write the results from an SQL query into text files. Write works fine however i want to be able to write all entries for the first time at once and subsequently add
all entries that aren't already in the file. Please do you know how this can be achieved?

  $t = mysql_query("SELECT text FROM transactions")
      or die("SELECT Error: ".mysql_error());


print "<table width=300 border=1>\n";
while ($get_info = mysql_fetch_row($t)){

$class = $op->classify($field); 

print "<tr>\n";
print "\t<td>Transaction</td>\n";
foreach ($get_info as $field)
print "\t<td>$field</td>\n";
print "\t<td>Type</td>\n";
foreach ($get_info as $field)
print "\t<td>$class</td>\n";
print "</tr>\n";


if ($class == "pos")
{
$filep = "positive.txt"; 
$handlep = fopen($filep, 'a');
$data = "$field\n";
fwrite($handlep, $data);

fclose($handlep); 


}
if ($class == "neg") {

$filen = "negative.txt"; 
$handlen = fopen($filen, 'a');
$datan = "$field\n";
fwrite($handlen, $datan);

fclose($handlen);

}

first, i can't imagine why you would ever want to do this, but here is how I would do it.

with each record, also store a timestamp in one of the columns. whenever you query the DB for new records to write, you do a query that only grabs records whose timestamps are later than the flat file's last modification time. the flat file of course being the file that you are doing the writes to.

you can use a simple filemtime($filename) to get your file's last modification time.

http://php.net/manual/en/function.filemtime.php

you might want to get a lock on the file before appending to it as well depending on how these writes are triggered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM