본문 바로가기
IT/Programming

Convert MySQL data To Json in PHP

by 여우요원 2019. 3. 28.

PHP에서 MySQL의 데이터를 JSON 으로 변환하기 !

<?php

// Initialize variable for database credentials
$dbhost = 'hostname';
$dbuser = 'username';
$dbpass = 'password';
$dbname = 'sakila';

//Create database connection
  $dblink = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

//Check connection was successful
  if ($dblink->connect_errno) {
     printf("Failed to connect to database");
     exit();
  }

//Fetch 3 rows from actor table
  $result = $dblink->query("SELECT * FROM actor LIMIT 3");

//Initialize array variable
  $dbdata = array();

//Fetch into associative array
  while ( $row = $result->fetch_assoc())  {
	$dbdata[]=$row;
  }

//Print array in JSON format
 echo json_encode($dbdata);
 
?>

 

출처 : https://www.opentechguides.com/how-to/article/php/100/mysql-to-json.html