Jump to content

PHP writing to .txt file


Rusty_Bad_Robot

Recommended Posts

I have a counter which takes it value from a .txt file - This value comes from the sum of a MySQL field - This script gets that value all I need to do is write it to the .txt??

 

<?php

// Make a MySQL Connection

 

$host="localhost";//hostname

$username="root";//username

$password="";//db_password

$db_name="db_name";//database name

 

//connect to database

mysql_connect("$host","$username","$password")or die("cannot connect to server");

mysql_select_db("$db_name")or die("cannot select database");

 

$query = "SELECT SUM(field) FROM table";

 

$result = mysql_query($query) or die(mysql_error());

 

// Print out result

while($row = mysql_fetch_array($result)){

echo $row['SUM(field)'];

echo "<br />";

}

?>

Link to comment
https://forums.phpfreaks.com/topic/195309-php-writing-to-txt-file/
Share on other sites

Thanks - It works great! I now need it to overwirite the file contents instead of just adding more information?

 

// Get Result

while($row = mysql_fetch_array($result)){

$filename = 'counter.txt';

$somecontent = $row['SUM(field)'];

}

 

// Let's make sure the file exists and is writable first.

if (is_writable($filename)) {

 

    // In our example we're opening $filename in append mode.

    // The file pointer is at the bottom of the file hence

    // that's where $somecontent will go when we fwrite() it.

    if (!$handle = fopen($filename, 'a')) {

        echo "Cannot open file ($filename)";

        exit;

    }

 

    // Write $somecontent to our opened file.

    if (fwrite($handle, $somecontent) === FALSE) {

        echo "Cannot write to file ($filename)";

        exit;

    }

 

    echo "Success, wrote ($somecontent) to file ($filename)";

 

    fclose($handle);

 

} else {

    echo "The file $filename is not writable";

}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.