Markcce Eros Markcce Eros - 1 month ago 9
PHP Question

PHP Looping table contacts and creating multiple files

I have some code where I access the database and fetch all the data from a table called snippets.

Everything works fine except I now need to create a new html file and save it with the contents of a field called code for each.

So basically each "code" field is saved as a new html file.

Here is the current code:

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT code FROM snippets";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {

//save each code record as a new html page

}
} else {
echo "0 results";
}
$conn->close();


How can I do that?

Answer

Try this...

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        // if you have id field in your record then try this way
        file_put_contents($row['id'].".html", $row); // 1 full path with name 2 your data

    }
} else {
    echo "0 results";
}
Comments