Skip to content

Instantly share code, notes, and snippets.

@ivankristianto
Last active November 22, 2019 12:09
Show Gist options
  • Save ivankristianto/f2e22dc283f7f5a3a2ee to your computer and use it in GitHub Desktop.
Save ivankristianto/f2e22dc283f7f5a3a2ee to your computer and use it in GitHub Desktop.
Export Import CSV
<?php
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
// open raw memory as file so no temp files needed, you might run out of memory though
$f = fopen('php://memory', 'w');
// loop over the input array
foreach ($array as $line) {
// generate csv lines from the inner arrays
fputcsv($f, $line, $delimiter);
}
// reset the file pointer to the start of the file
fseek($f, 0);
// tell the browser it's going to be a csv file
header('Content-Type: application/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachment; filename="'.$filename.'";');
// make php send the generated csv lines to the browser
fpassthru($f);
}
<?php
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
$conn = mysql_connect('localhost','username','password');
if($conn){
$db = mysql_select_db('ivankris_im4ukm',$conn);
}else{
die('Cannot connect to database!');
}
$query = mysql_query("SELECT * FROM `wp_imukm_members` Order BY status, id");
while($get = mysql_fetch_array($query)){
echo $get['id'].';'.$get['name'].';'.$get['email'].';'.$get['address'].';'.$get['phone'].';'.$get['status']."\n";
}
<?php
$conn = mysql_connect('localhost','root','');
if($conn){
$db = mysql_select_db('coba',$conn);
}else{
die('Cannot connect to database!');
}
$row = 1;
if (($handle = fopen("file.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$check = mysql_query("SELECT name FROM tbl_user WHERE id='".$data[0]."'");
if(!mysql_num_rows($check)){
if(!empty($data[0])){
mysql_query("INSERT INTO tbl_user VALUES('".$data[0]."','".$data[1]."','".$data[2]."','".$data[3]."','".$data[4]."')");
}
}
}
fclose($handle);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment