티스토리 뷰

[업데이트 2017.02.24 14:18]

 

REST API를 구현함에 있어서 Modern PHP 기능 중 하나인 PDO 객체를 이용하여 MySQL query부터 JSON 객체 생성까지 간단히 정리한 코드입니다.

<?php declare(strict_types=1);

    header("Content-Type: application/json; charset=UTF-8");

	$dbtype = 'mysql';
	$host = 'localhost';
	$dbname = 'scrapbook';
	$charset = 'utf8';

	$dsn = $dbtype.':host='.$host.';dbname='.$dbname.';charset='.$charset;

	$id = 'admin';
	$password = '1234';

	$conn = new PDO($dsn, $id, $password);

	$statement = $conn->prepare('select * from scraplist where idx = ? or content like ?');

	$idx = 3;

	// if you use ? placeholder, please use the index to bind each value.
	// They are indexed starting from 1 index. For example, they are 1,2,3,..,n.
	$statement->bindValue(1, $idx, PDO::PARAM_INT);
	$statement->bindValue(2, $idx, PDO::PARAM_STR);

	$statement->execute([$idx, '%arc%']);

	$record_cnt = 0;
	$record_array = [];

	while($row = $statement->fetch(PDO::FETCH_ASSOC))
	{
		array_push($record_array, array('idx' => (int)$row['idx'], 'content' =>$row['content']));
		$record_cnt++;
	}

	$json_result = [
		"status" => 200,
		"response" => [
			"total"=> $record_cnt, 
			"result" => $record_array
		]
	];

	echo  json_encode($json_result);
?>

 

HTTP request에 대해 php 페이지가 응답한 결과입니다.

{
	"status":200,
	"response":
	{
		"total":2,
		"result":
		[
			{"idx":1,"content":"http:\/\/arclab.tistory.com\r\n\ub098\uc758 \ud50c\ub85c\uadf8"},
			{"idx":3,"content":"http:\/\/www.coursera.com\r\nCoursera \uc628\ub77c\uc778 \uac15\uc758 \uc0ac\uc774\ud2b8"}
		]
	}
}

 

Firefox 개발자툴을 통한 JSON Object 결과 확인 입니다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함