728x90

MySQL DB 데이터를 csv 파일 형태로 저장하는 예제코드다.


<?php
$db['host'] = "localhost";
$db['name'] = "db명";
$db['user'] = "사용자id";
$db['pass'] = "비밀번호";
$db['port'] = "3306";
?>

<?php
include_once 'dbinfo.php';
$db = isConnectDb($db);

function isConnectDb($db)
{
    $conn = mysqli_connect($db['host'],$db['user'],$db['pass'],$db['name'],$db['port']);
    mysqli_set_charset($conn, "utf8"); 
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
        exit;
    } else {
        return $conn;
    }
}
?>

 <?php
$file_name = "cate_backup.xls";
header( "Content-type: application/vnd.ms-excel; charset=utf-8");
header( "Cache-Control: must-revalidate, post-check=0,pre-check=0" );
header( "Content-Disposition: attachment; filename=$file_name" );
header( "Content-Description: PHP4 Generated Data" );
//header() 함수를 쓰기전에 어떠한 출력도 있어선 안된다

include_once 'dbconect.php'; // DB 연동

$tblName = category;    // 테이블명
$sql ="SELECT uid, classname, relateduid FROM $tblName ORDER BY uid DESC";
// DESC 내림차순 정렬, ASC 오름차순 정렬
$result = mysqli_query($db,$sql);

// 테이블 상단 만들기
$EXCEL_STR = "
<table border='1'>
<tr>
<td align=center BGCOLOR='#9DEEE1'>번호</td>
<td align=center BGCOLOR='#9DEEE1'>구분자</td>
<td align=center BGCOLOR='#9DEEE1'>연관번호</td>
</tr>";

while ($row = mysqli_fetch_array($result) ){
    $EXCEL_STR .= "
    <tr>
    <td align=center>".$row['uid']."</td>
    <td align=center>".$row['classname']."</td>
    <td align=center>".$row['relateduid']."</td>
    </tr>
    ";
}

$EXCEL_STR .= "</table>";
echo $EXCEL_STR;
exit;
?>


블로그 이미지

Link2Me

,