Skip to content

Instantly share code, notes, and snippets.

@blinoale
Forked from umairidrees/PHP - Save DB Table as CSV
Created September 16, 2021 08:14
Show Gist options
  • Save blinoale/f361e6298c159cc6f93576f606dbec5b to your computer and use it in GitHub Desktop.
Save blinoale/f361e6298c159cc6f93576f606dbec5b to your computer and use it in GitHub Desktop.
<?php
$username="root"; $password=""; $database="exam_codes";
$con = mysql_connect("localhost",$username,$password) or die( "Unable to Connect database");
mysql_select_db($database,$con) or die( "Unable to select database");
// Table Name that you want
// to export in csv
$ShowTable = "blogs";
$FileName = "_export.csv";
$file = fopen($FileName,"w");
$sql = mysql_query("SELECT * FROM `$ShowTable` LIMIT 11");
$row = mysql_fetch_assoc($sql);
// Save headings alon
$HeadingsArray=array();
foreach($row as $name => $value){
$HeadingsArray[]=$name;
}
fputcsv($file,$HeadingsArray);
// Save all records without headings
while($row = mysql_fetch_assoc($sql)){
$valuesArray=array();
foreach($row as $name => $value){
$valuesArray[]=$value;
}
fputcsv($file,$valuesArray);
}
fclose($file);
header("Location: $FileName");
echo "Complete Record saves as CSV in file: <b style=\"color:red;\">$FileName</b>";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment