read all items from a MySQLi database table and save them into a text file

If you want to read all items from a MySQLi database table and save them into a text file, you can modify the previous example code like this:

// Connect to the database
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

// Select all data from the table
$sql = "SELECT name, email, phone, message FROM contact_form";
$result = $conn->query($sql);

// Check if any results were returned
if ($result->num_rows > 0) {
  // Create a string with the data for all rows
  $data = "";
  while ($row = $result->fetch_assoc()) {
    $data .= "Name: " . $row["name"] . "\n";
    $data .= "Email: " . $row["email"] . "\n";
    $data .= "Phone: " . $row["phone"] . "\n";
    $data .= "Message: " . $row["message"] . "\n\n";
  }

  // Write the data to a file
  $filename = "contact_data.txt";
  $file = fopen($filename, "w");
  fwrite($file, $data);
  fclose($file);

  echo "Data saved to file: " . $filename;
} else {
  echo "No results found.";
}

// Close the database connection
$conn->close();

In this modified code, we're selecting all rows from the contact_form table and creating a string with the data for each row using a while loop. We're also adding an extra newline character \n between each row to make the text file more readable.

Note that if you have a large amount of data in the table, you may want to consider paginating the results or limiting the number of rows returned to avoid memory issues. You can use the LIMIT and OFFSET clauses in the SQL query to achieve this.

Again, make sure to properly sanitize and validate user input to prevent SQL injection attacks and other security vulnerabilities, and handle any errors that may occur when reading from the database or writing to the file.

Related Articles

- All From ChatGPT
PLG_GSPEECH_SPEECH_BLOCK_TITLE