Page 1 of 1

PHP writing to .txt file

Posted: Mon Mar 15, 2010 7:56 am
by Rusty_Bad_Robot
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 />";
}
?>

Re: PHP writing to .txt file

Posted: Mon Mar 15, 2010 7:57 am
by papa
Why do you want to write the same values to a .txt when you have it stored in a db?

Re: PHP writing to .txt file

Posted: Mon Mar 15, 2010 8:10 am
by Rusty_Bad_Robot
I have my flash counter working from that .txt file - I could link it to the db but i've chosen to go this route.

Re: PHP writing to .txt file

Posted: Mon Mar 15, 2010 8:22 am
by papa
Ok, then all you need to do is to write that data to the file yes.

Re: PHP writing to .txt file

Posted: Mon Mar 15, 2010 8:29 am
by AbraCadaver

Code: Select all

file_put_contents('/path/to/your/file.txt', $data);

Re: PHP writing to .txt file

Posted: Mon Mar 15, 2010 8:30 am
by Rusty_Bad_Robot
Yeh - I have it working now... although 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";
}

Re: PHP writing to .txt file

Posted: Mon Mar 15, 2010 9:12 am
by Rusty_Bad_Robot
o.k just me being silly - had to change the mode for fopen.

Thanks for your help.

-Peace out -