Rusty_Bad_Robot Posted March 15, 2010 Share Posted March 15, 2010 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 More sharing options...
trq Posted March 15, 2010 Share Posted March 15, 2010 fopen, fwrite & fclose. Link to comment https://forums.phpfreaks.com/topic/195309-php-writing-to-txt-file/#findComment-1026336 Share on other sites More sharing options...
Rusty_Bad_Robot Posted March 15, 2010 Author Share Posted March 15, 2010 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"; } Link to comment https://forums.phpfreaks.com/topic/195309-php-writing-to-txt-file/#findComment-1026352 Share on other sites More sharing options...
Rusty_Bad_Robot Posted March 15, 2010 Author Share Posted March 15, 2010 o.k just me being silly - had to change the mode for fopen. Thanks for your help. -Peace out - Link to comment https://forums.phpfreaks.com/topic/195309-php-writing-to-txt-file/#findComment-1026383 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.