我有sql查询的php代码
count
此代码在浏览器上打印我的数据库名称 如何将数据库名称保存到文本文件
<?
$server = "127.0.0.1";
$username = "root";
$password = "1";
$link= connecttodb($server,$username,$password);
function connecttodb($server,$username,$password)
{
$rez=fopen("test.txt","ab");
if ($link=mysql_connect ("$server","$username","$password",TRUE))
{
fwrite($rez,"".$server." \r\n");
echo "Connected successfully to >> " .$server ;
$result = mysql_query('SHOW DATABASES');
echo "<br>";
while ($row = mysql_fetch_array($result))
{
var_dump ($row); }
}
}
ini_set('max_execution_time', 10);
return $link;
?>
答案 0 :(得分:30)
您可以使用输出缓冲功能捕获输出并将其写入文件。
ob_flush();
ob_start();
while ($row = mysql_fetch_assoc($result)) {
var_dump($row);
}
file_put_contents("dump.txt", ob_get_flush());
答案 1 :(得分:11)
不要为此使用var_dump,请使用序列化,如下所示:
<?php
$fp = fopen('vardump.txt', 'w');
fwrite($fp, serialize($myobj));
fclose($fp);
?>
要恢复它,可以使用unserialize($ filecontents);通过从文件中读回来。
答案 2 :(得分:0)
<?
$server = "127.0.0.1";
$username = "root";
$password = "1";
$link= connecttodb($server,$username,$password);
function connecttodb($server,$username,$password)
{
$rez=fopen("test.txt","ab");
if ($link=mysql_connect ("$server","$username","$password",TRUE))
{
fwrite($rez,"".$server." \r\n");
echo "Connected successfully to >> " .$server ;
$result = mysql_query('SHOW DATABASES');
echo "<br>";
while ($row = mysql_fetch_array($result))
{
fwrite($rez, $row['DatabaseName']); }
}
}
ini_set('max_execution_time', 10);
return $link;
?>
答案 3 :(得分:-3)
这应该有效
$file = 'somefile.txt';
file_put_contents($file, $some_var);
您可能希望首先序列化变量以使其更具可读性。
但还有其他几种方法:http://php.net/manual/en/function.file-put-contents.php