从 SQL 中提取数据,并写入文本文件 [英] Pulling data from SQL, and writing to a text file

查看:42
本文介绍了从 SQL 中提取数据,并写入文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 SQL 中提取数据,然后将其写入文本文件.这在一定程度上但它只从表中提取 1 个,该表读取文本文件中的 test:test
.

I am trying to pull data from SQL, and then write it to a text file. This does that, to an extent, but it only pulls 1 from the table, which reads test:test<br> on the text file.

我希望能够拉取所有数据从表中,然后发布到列表格式的文本文件,例如这……

I want to be able to pull all the data from the table, and then post to the text file in a list format such as this...

    test:test
    test2:test2
    test3:test3

我需要找出我做错了什么.

I need to find out what I am doing wrong.

<?php
$sql = mysql_query("SELECT * FROM _$setprofile ORDER BY fc DESC");
while($row = mysql_fetch_array($sql)){
$user = $row['user'];
$pass = $row['pass'];

$accounts = "$user:$pass<br>";

//Functionsss!
$file = "backups/$newcode.txt";
file_put_contents($file, $accounts);
}

echo "<a href=backups/$newcode.txt>TEST!</a>";
?>

推荐答案

file_put_contents() 函数会覆盖整个文件——这就是为什么你每次都只得到最后一条记录.

The file_put_contents() function overwrites the whole file - that's why you end up with only the last record each time.

您可以使用 fopen()fwrite() 代替.

You can use fopen() and fwrite() instead.

虽然比构建一个大字符串和使用一次对 file_put_contents 的调用稍微复杂一点,但如果您有很多记录,这不会耗尽内存.

While a little more complicated than building a large string and using a single call to file_put_contents, this won't run out of memory if you have a lot of records.

<?php

$file = "backups/$newcode.txt";
$f = fopen($file, 'w'); // Open in write mode

$sql = mysql_query("SELECT * FROM _$setprofile ORDER BY fc DESC");
while($row = mysql_fetch_array($sql))
{
    $user = $row['user'];
    $pass = $row['pass'];

    $accounts = "$user:$pass<br>";
    // Or "$user:$pass\n" as @Benjamin Cox points out

    fwrite($f, $accounts);
}

fclose($f);

echo "<a href=backups/$newcode.txt>TEST!</a>";
?>

这篇关于从 SQL 中提取数据,并写入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆