Jump to content

[SOLVED] Help writing to a text file


affordit

Recommended Posts

I am trying to pull a random record from my database and write it to a text file but can't get it to work can someone help please thanks.

this is what I have so far

<?php
  include "file_func.php";
include("sharons_dbinfo.inc.php");
mysql_connect(mysql,$name,$password);
mysql_select_db($database) or die( "Unable to select database"); 

$range_result = mysql_query( " SELECT MAX(`id`) AS max_id , MIN(`id`) AS min_id FROM `login` ");
$range_row = mysql_fetch_object( $range_result ); 
$random = mt_rand( $range_row->min_id , $range_row->max_id );
$result = mysql_query( " SELECT * FROM `login` WHERE `id` >= $random LIMIT 0,1 ");


  append_file('test.txt', '$result['id']<br>~<br>');
  $data=read_file('test.txt');

   echo "Data in file : <b>$data</b>";

?>

Link to comment
https://forums.phpfreaks.com/topic/92489-solved-help-writing-to-a-text-file/
Share on other sites

Looking at your code I see one error, which is the following line:

append_file('test.txt', '$result['id']<br>~<br>');

Variables do not get parsed when inside single quotes you should use double quotes, or better still use concatenation:

# concatenation:
append_file('test.txt', $result['id'] . '<br>~<br>');

# double qoutes:
append_file('test.txt', "{$result['id']}<br>~<br>");

I could not reply to your last post I tried the code you posted but all it puts in the file is the ~

I didn't thuroughly read your code. mysql_query doesn't return rows, it only returns the result resource. You'll need to use one of the various mysql_fetch_*() functions (* standing for row, array or assoc or object). I recommend mysql_fetch_assoc. So the following few lines:

$result = mysql_query( " SELECT * FROM `login` WHERE `id` >= $random LIMIT 0,1 ");


  append_file('test.txt', '$result['id']<br>~<br>');

Should be:

$result = mysql_query( " SELECT * FROM `login` WHERE `id` >= $random LIMIT 0,1 "); // run query
$row = mysql_fetch_assoc($result); // return results

append_file('test.txt', $row['id'] . '<br>~<br>');

 

If you query returns more than one row you'll need to use a while loop, eg:

$result = mysql_query( " SELECT * FROM `login` WHERE `id` >= $random LIMIT 0,1 "); // run query

// loop through results
while($row = mysql_fetch_assoc($result))
{
    append_file('test.txt', $row['id'] . '<br>~<br>');
}

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.