【问题标题】:How do I save the output of this code into a file? (PHP) [closed]如何将此代码的输出保存到文件中? (PHP) [关闭]
【发布时间】:2016-05-14 19:46:16
【问题描述】:

这段代码循环了一些mysql表:

foreach($tables as $table)
{
echo "<h2>" . $table[0] . "</h2>";
$query = "DESCRIBE " . $table[0];
$result = $mysqli->query($query);

$columns = $result->fetch_all();

foreach($columns as $column)
{
    echo $column[0]. '<br />';
}
}

如何让它输出到文件? (只是表名和列名)

【问题讨论】:

  • 在foreach循环之前使用fopen()打开一个文件进行写入(模式w);使用fwrite() 写入foreach 循环内的文件;使用 fclose() 在 foreach 循环后关闭文件

标签: php mysql file


【解决方案1】:

您可以使用 fopen 和 fwrite PHP 函数来执行此操作。

应该是这样的:

<?php

// Here we create a file handler
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");

foreach($tables as $table)
{
    echo "<h2>" . $table[0] . "</h2>";
    // Here, we write the value of $table[0] and a new line in the file
    fwrite($myfile, "Table " . $table[0] . "\n");

    $query = "DESCRIBE " . $table[0];
    $result = $mysqli->query($query);

    $columns = $result->fetch_all();

    foreach($columns as $column)
    {
        echo $column[0]. '<br />';
        fwrite($myfile, " - " . $column[0] . "\n");
    }
}
fclose($myfile);

?>

注意:我强烈建议您对 SQL 查询使用准备好的语句。

【讨论】:

  • 谢谢,成功了。
猜你喜欢
  • 1970-01-01
  • 2014-03-17
  • 1970-01-01
  • 2013-01-17
  • 2022-07-15
  • 1970-01-01
  • 2013-05-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多