This weekend, I needed to construct a PHP web page that might again up any MySQL question or desk right into a Tab Delimited file. Many of the examples out on the web have the columns hard-coded.
In my case, I needed the columns to be dynamic, so I needed to first loop by way of all of the desk subject names to construct the header row with column names after which loop by way of all of the information for the remaining information rows. I additionally set the header in order that the browser will provoke the file obtain within the filetype (txt) with the title of the file date and timestamped.
Tab Delimited Export From MySQL in PHP
<?php
$right this moment = date("YmdHi");
header("Content material-type: software/octet-stream");
header("Content material-Disposition: attachment; filename="".$right this moment."_Backup.txt"");
$conn = new mysqli("hostname", "username", "password", "database_name"); // Change along with your database credentials
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$question = "SELECT * FROM `mytable` ORDER BY `myorder`";
$outcome = $conn->question($question);
if ($result->num_rows > 0) {
$fields = $result->fetch_fields();
// Put together the header row
$header = [];
foreach ($fields as $subject) {
$header[] = $field->title;
}
$information = implode("t", $header) . "n";
// Fetch and course of the info rows
whereas ($row = $result->fetch_assoc()) {
$rowValues = [];
foreach ($fields as $subject) {
$rowValues[] = $row[$field->name];
}
$information .= implode("t", $rowValues) . "n";
}
// Output the info
echo $information;
} else {
echo "No information discovered";
}
// Shut the database connection
$conn->shut();
?>
Let’s stroll by way of the code step-by-step with explanations for every half:
<?php
// Get the present date and time in a particular format
$right this moment = date("YmdHi");
// Set HTTP headers for file obtain
header("Content material-type: software/octet-stream");
header("Content material-Disposition: attachment; filename="".$right this moment."_Backup.txt"");
// Create a MySQL database connection
$conn = new mysqli("hostname", "username", "password", "database_name"); // Change along with your database credentials
// Verify if the database connection was profitable
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
- We generate the present date and time within the “YmdHi” format and retailer it within the
$right this moment
variable. - HTTP headers are set to specify that the content material needs to be handled as an octet-stream (binary information) and set off a file obtain with the required filename.
- Utilizing the extension, we create a MySQL database connection, changing placeholders along with your precise database credentials.
- We test if the database connection was profitable. We terminate the script and show an error message if there’s an error.
// Outline the SQL question to pick out information from the `mytable` desk
$question = "SELECT * FROM `mytable` ORDER BY `myorder`";
// Execute the SQL question
$outcome = $conn->question($question);
// Verify if there are any rows returned
if ($result->num_rows > 0) {
// Fetch the sector (column) names
$fields = $result->fetch_fields();
// Put together the header row for the export file
$header = [];
foreach ($fields as $subject) {
$header[] = $field->title;
}
$information = implode("t", $header) . "n";
- We outline the SQL question to pick out all information from the
mytable
desk, ordering it by themyorder
column. - The question is executed, and the result’s saved within the
$outcome
variable. - We test if there are any rows returned by analyzing the
num_rows
property of the outcome object. - We use
fetch_fields()
to retrieve the sector (column) names and retailer them within the$fields
array. - The header row for the export file is ready by looping by way of the sector names and concatenating them with tabs.
// Fetch and course of the info rows
whereas ($row = $result->fetch_assoc()) {
$rowValues = [];
foreach ($fields as $subject) {
$rowValues[] = $row[$field->name];
}
$information .= implode("t", $rowValues) . "n";
}
- We use a
whereas
loop to fetch every information row from the outcome set utilizingfetch_assoc()
. - Contained in the loop, we put together the values of every row by iterating by way of the fields and amassing the corresponding information.
- The values for every row are concatenated with tabs to create a tab-delimited row, and this row is added to the
$information
variable.
// Output the info to the browser
echo $information;
} else {
// If no information is discovered, show a message
echo "No information discovered";
}
// Shut the MySQL database connection
$conn->shut();
?>
- If there may be information discovered (checked with
num_rows
), we echo the concatenated information, which is the content material of the export file. This triggers the file obtain within the consumer’s browser. - If no information is discovered, we show a message indicating that no information is accessible.
- We shut the MySQL database connection utilizing
$conn->shut()
to launch sources.
This code effectively exports information from a MySQL database desk right into a tab-delimited textual content file and handles numerous eventualities, akin to database connection errors and empty outcome units.
Comma-Separated Values Export From MySQL in PHP
I can modify the code to export information as a CSV file. Right here’s the code, up to date for CSV export:
<?php
// Get the present date and time in a particular format
$right this moment = date("YmdHi");
// Set HTTP headers for file obtain
header("Content material-type: textual content/csv");
header("Content material-Disposition: attachment; filename="".$right this moment."_Backup.csv"");
// Create a MySQL database connection
$conn = new mysqli("hostname", "username", "password", "database_name"); // Change along with your database credentials
// Verify if the database connection was profitable
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Outline the SQL question to pick out information from the `mytable` desk
$question = "SELECT * FROM `mytable` ORDER BY `myorder`";
// Execute the SQL question
$outcome = $conn->question($question);
// Verify if there are any rows returned
if ($result->num_rows > 0) {
// Put together the output file deal with for writing
$output = fopen('php://output', 'w');
// Fetch and course of the info rows
whereas ($row = $result->fetch_assoc()) {
// Output every row as a CSV line
fputcsv($output, $row);
}
// Shut the output file deal with
fclose($output);
} else {
// If no information is discovered, show a message
echo "No information discovered";
}
// Shut the MySQL database connection
$conn->shut();
?>
On this modified code:
- The headers for the HTTP response are up to date to specify a
textual content/csv
content material sort, and the filename has the “.csv” extension. - As an alternative of manually creating the CSV content material, we use the
fputcsv
perform to output every row from the MySQL outcome set as a CSV line. This perform handles the CSV formatting for you, together with dealing with particular characters and enclosing fields in double quotes when crucial. - We open the output file deal with utilizing
fopen
with ‘php://output’ because the file title. This enables us to jot down on to the HTTP response output stream. - The code is structured to deal with CSV export effectively and closes the file deal with when achieved.
This code will export the info from the MySQL desk as a CSV file, making it straightforward for customers to open and work with in spreadsheet functions like Excel. Don’t neglect to switch the database credentials with your individual.