ta_acc_ k ta_acc_ k - 6 months ago 24
SQL Question

How do I save the output of this code into a file? (PHP)

This code that loops through some mysql tables:

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 />';
}
}


How do I make it output to a file? (Just the names of the tables and the column names)

Answer

You can use the fopen and fwrite PHP functions to do that.

It would be something like this:

<?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);

?>

Note: I strongly recommend you to use prepared statements for the SQL queries.