-
[php] mysqli to json프로그래밍/Web(CSS + HTML + JS + PHP ) 2019. 3. 22. 15:11728x90
d3.js를 사용하다보면 데이터를 json이나 csv를 이용하여 참조한다.
php에선 sql를 이용하여 데이터를 저장하기 때문에 mysqli를 이용하여 json을 출력할 수 있는 방법을 소개하고자 한다.
db.php
123456789101112131415161718192021222324<?phpsession_start();header('Content-Type: text/html; charset=utf-8'); // utf-8인코딩$db = new mysqli('localhost','db아이디','db비밀번호','데이터베이스명');$db->set_charset('utf8');if($db->connect_error) {die('데이터베이스 연결에 문제가 있습니다.\n관리자에게 문의 바랍니다.');}function pqi($data){global $db;return $db->real_escape_string($data);}function mq($sql){global $db;return $db->query($sql);}?>cs json.php
1234567891011<?phpinclude "db.php";?><?php$myArray = array();$result = mq("select * from 테이블명");while($row = $result->fetch_array(MYSQLI_ASSOC)) {$myArray[] = $row;}echo json_encode($myArray);?>cs d3.js의 json read구문에 json.php로 대체하면 된다.
728x90댓글