简体   繁体   中英

Records are not coming in textfile from mysql

Here, I want to fetch record from mysql to textfile that I am writing into textfile.
But textfile is creating as blank.
Where is the problem?

My code:

$myFile = 'abctest.txt';
//echo $myFile;exit;
$fo = fopen('com_order/order_textfile/'.$myFile, 'w+') or die("can't open file");

$data_query=mysql_query("SELECT order_id from tbl_order") or die(mysql_error());

while($data=mysql_fetch_array($data_query))
{
    $stringData = fwrite($fo, "Order: ".$data['order_id']."\n");
}
fwrite($fo, $stringData);
fclose($fo);

header('Content-type: text/plain');
header('Content-disposition: attachment; filename='.$myFile);

readfile() call is missing:

readfile($myFile);

So it should look like this:

header('Content-type: text/plain');
header('Content-disposition: attachment; filename='.$myFile);
readfile($myFile);

Here readfile() is the function which actually performs all the hard work (reads the file, writes to output).

More on the topic:

readfile()

Force download

UPDATE

Also you have a file path problem

Note that you create file in com_order/order_textfile/'.$myFile but then use $myFile without the path. When referencing file you should use path instead:

$myFile = 'abctest.txt';
$filePath = 'com_order/order_textfile/'.$myFile;
$fo = fopen($filePath, 'w+') or die("can't open file");

$data_query=mysql_query("SELECT order_id from tbl_order") or die(mysql_error());

while($data=mysql_fetch_array($data_query))
{
    $stringData = fwrite($fo, "Order: ".$data['order_id']."\n");
}
fwrite($fo, $stringData);
fclose($fo);

header('Content-type: text/plain');
header('Content-disposition: attachment; filename='.$filePath);
readfile($filePath);

It seems like there is a problem with the way you execute your query but try the code below it's working.

$link = mysqli_connect("localhost", "username", "password", "database name") or die("error unable to connect to database". mysqli_error($link)); 

$myFile = 'abctest.txt';
//echo $myFile;exit;
$fo = fopen('com_order/order_textfile/'.$myFile, 'w+') or die("can't open file");

$data_query=$link->query("SELECT order_id from tbl_order") or die(mysql_error());

while($data=mysqli_fetch_array($data_query))
{
    $stringData = fwrite($fo, "Order: ".$data['order_id']."\n");
    //echo("$stringData");
}
fwrite($fo, $stringData);
fclose($fo);

header('Content-type: text/plain');
header('Content-disposition: attachment; filename='.$myFile);

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