오늘은 JavaScript 프로그래밍을 시작하기 전에 PHP로 간단한 REST API를 만드는 방법을 배웁니다. 아래의 단계별 자습서를 즐기십시오!
이 게시물은 다음 주제를 다룹니다.
1.0 프로젝트 개요
1.1 REST API란 무엇입니까?
1.2 REST API가 필요한 이유는 무엇입니까?
1.3 REST API는 어디에 사용됩니까?
1.4 튜토리얼의 REST API
2.0 파일 구조
3.0 데이터베이스 설정
3.1 카테고리 테이블 생성
3.2 카테고리 테이블의 덤프 데이터
3.3 제품 표
3.4 제품 테이블의 덤프 데이터
3.5 데이터베이스에 연결
4.0 제품 읽기
4.1 제품 개체
4.2 제품을 읽을 파일 만들기
4.3 데이터베이스 및 제품 테이블에 연결
4.4 데이터베이스에서 제품 읽기
4.5 제품 "read()"메서드 추가
4.6 사용자에게 제품을 찾을 수 없음을 알립니다.
4.7 출력
5.0 제품 생성
5.1 create.php 파일 생성
5.2 제품 create() 메서드
5.3 출력
6.0 하나의 제품 읽기
6.1 read_one.php 파일 생성
6.2 제품 readOne() 메서드
6.3 출력
7.0 제품 업데이트
7.1“update.php”파일 생성
7.2 제품 update() 메서드
7.3 출력
8.0 제품 삭제
8.1“delete.php”파일 생성
8.2 제품 delete() 메서드
8.3 출력
9.0 제품 검색
9.1 "search.php"파일 생성
9.2 "search()"메서드 생성
9.3 출력
10.0 페이지 매김 제품
10.1 "read_paging.php"파일 생성
10.2 "core.php"파일 생성
10.3 "readPaging()"메서드 생성
10.4 "count()"메서드 생성
10.5 "페이징"배열 가져 오기
10.6 출력
11.0 범주 읽기
11.1 카테고리 객체
11.2 "read.php"파일 생성
11.3 카테고리 "read()"메서드
11.4 출력
12.0 소스 코드 다운로드
13.0 다음은?
14.0 관련 튜토리얼
15.0 참고
https://codeofaninja.com/2017/02/create-simple-rest-api-in-php.html
1.0 프로젝트 개요
1.1 REST API 란 무엇입니까?
"REST API"를 정의하려면 먼저 "REST"와 "API"가 무엇인지 알아야 합니다. REST에는 많은 것을 의미 할 수 있는 많은 개념이 포함되어 있기 때문에 간단한 용어로 설명하기 위해 최선을 다할 것입니다.
REST는 "REpresentational State Transfer"를 의미합니다. 인터넷을 통해 정보를 관리하기 위한 개념 또는 아키텍처입니다. REST 개념을 리소스라고 합니다. 리소스 표현은 상태 비 저장이어야 합니다. 일반적으로 JSON으로 표시됩니다. 이 게시물은 읽을 가치가 있습니다. 아내에게 REST를 어떻게 설명했습니까?
API는 "Application Programming Interface"를 의미합니다. 한 소프트웨어 응용 프로그램이 다른 응용 프로그램과 통신 할 수 있도록 하는 규칙 집합입니다. 이러한 "규칙"에는 만들기, 읽기, 업데이트 및 삭제 작업이 포함될 수 있습니다.
REST API를 사용하면 애플리케이션이 REST 개념을 사용하여 하나 이상의 서로 다른 애플리케이션과 협력 할 수 있습니다. 자세한 내용은 아래 비디오를 참조하십시오.
1.2 REST API가 필요한 이유는 무엇입니까?
많은 애플리케이션에서 REST API는 인터넷 또는 HTTP 프로토콜을 통해 서로 다른 애플리케이션 간에 정보를 생성, 읽기, 업데이트 또는 삭제하는 가장 가벼운 방법이기 때문에 필요합니다. 이 정보는 특히 JavaScript를 사용하여 웹 페이지에서 데이터를 렌더링 하는 경우 사용자에게 즉시 표시됩니다.
1.3 REST API는 어디에 사용됩니까?
REST API는 인터넷에 연결할 수 있는 모든 애플리케이션에서 사용할 수 있습니다. 다른 애플리케이션을 사용하여 애플리케이션의 데이터를 생성, 읽기, 업데이트 또는 삭제할 수 있다면 일반적으로 REST API가 사용됨을 의미합니다.
1.4 튜토리얼의 REST API
AJAX CRUD 튜토리얼에는 REST API가 필요합니다. 그러나 지금은 신경 쓰지 마십시오. 한 번에 한 단계씩 수행합니다. 모든 것을 배울 필요는 없습니다. 배워야 할 것을 선택하십시오.
또한 이 PHP REST API는 아직 최종 형태가 아닙니다. 더 나은 URL 등을 위해 .htaccess와 관련된 작업이 아직 남아 있습니다.
하지만 한 가지는 확실합니다. 이 소스 코드는 충분하며 JavaScript 튜토리얼에서 작동합니다.
2.0 파일 구조
이 튜토리얼이 끝나면 다음과 같은 폴더와 파일을 갖게 됩니다.
├─ api/
├─── config/
├────── core.php - 핵심 구성에 사용되는 파일
├────── database.php - 데이터베이스에 연결하는 데 사용되는 파일입니다.
├─── objects/
├────── product.php - "제품"데이터베이스 쿼리에 대한 속성 및 메서드를 포함합니다.
├────── category.php - "범주"데이터베이스 쿼리에 대한 속성 및 메서드를 포함합니다.
├─── product/
├────── create.php - 게시 된 제품 데이터를 허용하는 파일이 데이터베이스에 저장됩니다.
├────── delete.php - 데이터베이스 레코드를 삭제하기 위해 제품 ID를 허용하는 파일.
├────── read.php - "제품"데이터베이스 레코드를 기반으로 JSON 데이터를 출력하는 파일입니다.
├────── read_paging.php - 페이지 매김과 함께 "제품"JSON 데이터를 출력하는 파일입니다.
├────── read_one.php - 데이터베이스에서 레코드를 읽기 위해 제품 ID를 허용하는 파일.
├────── update.php - 데이터베이스 레코드를 업데이트하기 위해 제품 ID를 허용하는 파일.
├────── search.php - "제품"데이터베이스를 검색하기 위해 키워드 매개 변수를 허용하는 파일.
├─── category/
├────── read.php - "카테고리"데이터베이스 레코드를 기반으로 JSON 데이터를 출력하는 파일입니다.
├─── shared/
├────── utilities.php - 페이지 매김 배열을 반환 할 파일.
3.0 데이터베이스 설정
PhpMyAdmin을 사용하여 새 api_db 데이터베이스를 만듭니다. 예, api_db는 데이터베이스 이름입니다. 그런 다음 다음 SQL 쿼리를 실행하여 샘플 데이터로 새 테이블을 만듭니다.
3.1 카테고리 테이블 생성
CREATE
TABLE
IF
NOT
EXISTS `categories` (
`id`
int
(11)
NOT
NULL
AUTO_INCREMENT,
`
name
`
varchar
(256)
NOT
NULL
,
`description` text
NOT
NULL
,
`created` datetime
NOT
NULL
,
`modified`
timestamp
NOT
NULL
DEFAULT
CURRENT_TIMESTAMP
,
PRIMARY
KEY
(`id`)
) ENGINE=InnoDB
DEFAULT
CHARSET=utf8 AUTO_INCREMENT=19 ;
3.2 카테고리 테이블의 덤프 데이터
INSERT
INTO
`categories` (`id`, `
name
`, `description`, `created`, `modified`)
VALUES
(1,
'Fashion'
,
'Category for anything related to fashion.'
,
'2014-06-01 00:35:07'
,
'2014-05-30 17:34:33'
),
(2,
'Electronics'
,
'Gadgets, drones and more.'
,
'2014-06-01 00:35:07'
,
'2014-05-30 17:34:33'
),
(3,
'Motors'
,
'Motor sports and more'
,
'2014-06-01 00:35:07'
,
'2014-05-30 17:34:54'
),
(5,
'Movies'
,
'Movie products.'
,
'0000-00-00 00:00:00'
,
'2016-01-08 13:27:26'
),
(6,
'Books'
,
'Kindle books, audio books and more.'
,
'0000-00-00 00:00:00'
,
'2016-01-08 13:27:47'
),
(13,
'Sports'
,
'Drop into new winter gear.'
,
'2016-01-09 02:24:24'
,
'2016-01-09 01:24:24'
);
3.3 제품 표
CREATE
TABLE
IF
NOT
EXISTS `products` (
`id`
int
(11)
NOT
NULL
AUTO_INCREMENT,
`
name
`
varchar
(32)
NOT
NULL
,
`description` text
NOT
NULL
,
`price`
decimal
(10,0)
NOT
NULL
,
`category_id`
int
(11)
NOT
NULL
,
`created` datetime
NOT
NULL
,
`modified`
timestamp
NOT
NULL
DEFAULT
CURRENT_TIMESTAMP
,
PRIMARY
KEY
(`id`)
) ENGINE=InnoDB
DEFAULT
CHARSET=latin1 AUTO_INCREMENT=65 ;
3.4 제품 테이블의 덤프 데이터
INSERT
INTO
`products` (`id`, `
name
`, `description`, `price`, `category_id`, `created`, `modified`)
VALUES
(1,
'LG P880 4X HD'
,
'My first awesome phone!'
,
'336'
, 3,
'2014-06-01 01:12:26'
,
'2014-05-31 17:12:26'
),
(2,
'Google Nexus 4'
,
'The most awesome phone of 2013!'
,
'299'
, 2,
'2014-06-01 01:12:26'
,
'2014-05-31 17:12:26'
),
(3,
'Samsung Galaxy S4'
,
'How about no?'
,
'600'
, 3,
'2014-06-01 01:12:26'
,
'2014-05-31 17:12:26'
),
(6,
'Bench Shirt'
,
'The best shirt!'
,
'29'
, 1,
'2014-06-01 01:12:26'
,
'2014-05-31 02:12:21'
),
(7,
'Lenovo Laptop'
,
'My business partner.'
,
'399'
, 2,
'2014-06-01 01:13:45'
,
'2014-05-31 02:13:39'
),
(8,
'Samsung Galaxy Tab 10.1'
,
'Good tablet.'
,
'259'
, 2,
'2014-06-01 01:14:13'
,
'2014-05-31 02:14:08'
),
(9,
'Spalding Watch'
,
'My sports watch.'
,
'199'
, 1,
'2014-06-01 01:18:36'
,
'2014-05-31 02:18:31'
),
(10,
'Sony Smart Watch'
,
'The coolest smart watch!'
,
'300'
, 2,
'2014-06-06 17:10:01'
,
'2014-06-05 18:09:51'
),
(11,
'Huawei Y300'
,
'For testing purposes.'
,
'100'
, 2,
'2014-06-06 17:11:04'
,
'2014-06-05 18:10:54'
),
(12,
'Abercrombie Lake Arnold Shirt'
,
'Perfect as gift!'
,
'60'
, 1,
'2014-06-06 17:12:21'
,
'2014-06-05 18:12:11'
),
(13,
'Abercrombie Allen Brook Shirt'
,
'Cool red shirt!'
,
'70'
, 1,
'2014-06-06 17:12:59'
,
'2014-06-05 18:12:49'
),
(26,
'Another product'
,
'Awesome product!'
,
'555'
, 2,
'2014-11-22 19:07:34'
,
'2014-11-21 20:07:34'
),
(28,
'Wallet'
,
'You can absolutely use this one!'
,
'799'
, 6,
'2014-12-04 21:12:03'
,
'2014-12-03 22:12:03'
),
(31,
'Amanda Waller Shirt'
,
'New awesome shirt!'
,
'333'
, 1,
'2014-12-13 00:52:54'
,
'2014-12-12 01:52:54'
),
(42,
'Nike Shoes for Men'
,
'Nike Shoes'
,
'12999'
, 3,
'2015-12-12 06:47:08'
,
'2015-12-12 05:47:08'
),
(48,
'Bristol Shoes'
,
'Awesome shoes.'
,
'999'
, 5,
'2016-01-08 06:36:37'
,
'2016-01-08 05:36:37'
),
(60,
'Rolex Watch'
,
'Luxury watch.'
,
'25000'
, 1,
'2016-01-11 15:46:02'
,
'2016-01-11 14:46:02'
);
3.5 데이터베이스에 연결
아래 코드는 데이터베이스 자격 증명과 PDO를 사용하여 데이터베이스 연결을 얻는 방법을 보여줍니다. 아직 PDO에 익숙하지 않다면 먼저 PHP OOP CRUD Tutorial에서 배우십시오.
<?php
class
Database{
// specify your own database credentials
private
$host
=
"localhost"
;
private
$db_name
=
"api_db"
;
private
$username
=
"root"
;
private
$password
=
""
;
public
$conn
;
// get the database connection
public
function
getConnection(){
$this
->conn = null;
try
{
$this
->conn =
new
PDO(
"mysql:host="
.
$this
->host .
";dbname="
.
$this
->db_name,
$this
->username,
$this
->password);
$this
->conn->
exec
(
"set names utf8"
);
}
catch
(PDOException
$exception
){
echo
"Connection error: "
.
$exception
->getMessage();
}
return
$this
->conn;
}
}
?>
4.0 제품 읽기
4.1 제품 개체
아래 코드는 여러 속성이 있는 Product라는 클래스를 보여줍니다. 또한 데이터베이스 연결을 허용하는 생성자 메서드를 보여줍니다.
이 클래스를 사용하여 데이터베이스에서 데이터를 읽습니다.
<?php
class
Product{
// database connection and table name
private
$conn
;
private
$table_name
=
"products"
;
// object properties
public
$id
;
public
$name
;
public
$description
;
public
$price
;
public
$category_id
;
public
$category_name
;
public
$created
;
// constructor with $db as database connection
public
function
__construct(
$db
){
$this
->conn =
$db
;
}
}
?>
4.2 제품을 읽을 파일 생성
아래 코드는 이 파일을 읽을 수 있는 사람과 반환 할 콘텐츠 유형에 대한 헤더를 보여줍니다.
이 경우 read.php 파일은 누구나 읽을 수 있으며 (별표 *는 모두 의미) JSON 형식으로 데이터를 반환합니다.
<?php
// required headers
header(
"Access-Control-Allow-Origin: *"
);
header(
"Content-Type: application/json; charset=UTF-8"
);
// database connection will be here
4.3 데이터베이스 및 제품 테이블에 연결
아래 코드에는 database.php 및 product.php 파일이 포함되어 있습니다. 이전에 만든 파일입니다.
데이터베이스 연결을 얻으려면 Database 클래스의 getConnection() 메서드를 사용해야 합니다. 이 연결을 Product 클래스에 전달합니다.
// 데이터베이스 연결의 대체는 다음 코드로 read.php 파일의 주석입니다.
// include database and object files
include_once
'../config/database.php'
;
include_once
'../objects/product.php'
;
// instantiate database and product object
$database
=
new
Database();
$db
=
$database
->getConnection();
// initialize object
$product
=
new
Product(
$db
);
// read products will be here
4.4 데이터베이스에서 제품 읽기
아래 코드에서는 Product 클래스의 read() 메서드를 사용하여 데이터베이스에서 데이터를 읽었습니다. $num 변수를 통해 레코드가 있는지 확인합니다.
레코드가 발견되면 while 루프를 사용하여 반복하고 각 레코드를 $products_arr 배열에 추가하고 200 OK 응답 코드를 설정하고 JSON 형식으로 사용자에게 표시합니다.
// read 제품의 대체는 다음 코드로 read.php 파일의 주석이 됩니다.
// query products $stmt = $product ->read(); $num = $stmt ->rowCount(); // check if more than 0 record found if ( $num >0){ // products array $products_arr = array (); $products_arr [ "records" ]= array (); // retrieve our table contents // fetch() is faster than fetchAll() while ( $row = $stmt ->fetch(PDO::FETCH_ASSOC)){ // extract row // this will make $row['name'] to // just $name only extract( $row ); $product_item = array ( "id" => $id , "name" => $name , "description" => html_entity_decode( $description ), "price" => $price , "category_id" => $category_id , "category_name" => $category_name ); array_push ( $products_arr [ "records" ], $product_item ); } // set response code - 200 OK http_response_code(200); // show products data in json format echo json_encode( $products_arr ); } // no products found will be here |
4.5 제품 "read()"메서드 추가
이전 섹션에서 read() 메서드를 사용했지만 아직 Product 클래스에 존재하지 않습니다. 이 read() 메서드를 추가해야 합니다. 아래 코드는 데이터베이스에서 레코드를 가져 오는 쿼리를 보여줍니다.
// read products
function
read(){
// select all query
$query
= "SELECT
c.name
as
category_name, p.id, p.name, p.description, p.price, p.category_id, p.created
FROM
" . $this->table_name . "
p
LEFT JOIN
categories c
ON p.category_id = c.id
ORDER BY
p.created DESC";
// prepare query statement
$stmt
=
$this
->conn->prepare(
$query
);
// execute query
$stmt
->execute();
return
$stmt
;
}
4.6 사용자에게 제품을 찾을 수 없음을 알립니다.
$num 변수의 값이 0이거나 음수이면 데이터베이스에서 반환 된 레코드가 없음을 의미합니다. 사용자에게 이에 대해 알려야 합니다.
아래 코드에서 응답 코드를 404-찾을 수 없음으로 설정하고 제품을 찾을 수 없음이라는 메시지를 표시합니다.
// no products를 대체하면 여기에 read.php 파일의 주석이 다음 코드로 표시됩니다.
else { // set response code - 404 Not found http_response_code(404); // tell the user no products found echo json_encode( array ( "message" => "No products found." ) ); } |
4.7 출력
API를 테스트하려면 POSTMAN을 사용해야 합니다. 여기에서 POSTMAN 버전을 다운로드하십시오.
POSTMAN을 시작합니다. 요청 URL로 다음을 입력하십시오.
파란색 "보내기"버튼을 클릭합니다.
5.0 제품 생성
5.1 create.php 파일 생성
<?php
// required headers
header(
"Access-Control-Allow-Origin: *"
);
header(
"Content-Type: application/json; charset=UTF-8"
);
header(
"Access-Control-Allow-Methods: POST"
);
header(
"Access-Control-Max-Age: 3600"
);
header(
"Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
);
// get database connection
include_once
'../config/database.php'
;
// instantiate product object
include_once
'../objects/product.php'
;
$database
=
new
Database();
$db
=
$database
->getConnection();
$product
=
new
Product(
$db
);
// get posted data
$data
= json_decode(
file_get_contents
(
"php://input"
));
// make sure data is not empty
if
(
!
empty
(
$data
->name) &&
!
empty
(
$data
->price) &&
!
empty
(
$data
->description) &&
!
empty
(
$data
->category_id)
){
// set product property values
$product
->name =
$data
->name;
$product
->price =
$data
->price;
$product
->description =
$data
->description;
$product
->category_id =
$data
->category_id;
$product
->created =
date
(
'Y-m-d H:i:s'
);
// create the product
if
(
$product
->create()){
// set response code - 201 created
http_response_code(201);
// tell the user
echo
json_encode(
array
(
"message"
=>
"Product was created."
));
}
// if unable to create the product, tell the user
else
{
// set response code - 503 service unavailable
http_response_code(503);
// tell the user
echo
json_encode(
array
(
"message"
=>
"Unable to create product."
));
}
}
// tell the user data is incomplete
else
{
// set response code - 400 bad request
http_response_code(400);
// tell the user
echo
json_encode(
array
(
"message"
=>
"Unable to create product. Data is incomplete."
));
}
?>
5.2 제품 create() 메서드
// create product
function
create(){
// query to insert record
$query
= "INSERT INTO
" . $this->table_name . "
SET
name=:name, price=:price, description=:description, category_id=:category_id, created=:created";
// prepare query
$stmt
=
$this
->conn->prepare(
$query
);
// sanitize
$this
->name=htmlspecialchars(
strip_tags
(
$this
->name));
$this
->price=htmlspecialchars(
strip_tags
(
$this
->price));
$this
->description=htmlspecialchars(
strip_tags
(
$this
->description));
$this
->category_id=htmlspecialchars(
strip_tags
(
$this
->category_id));
$this
->created=htmlspecialchars(
strip_tags
(
$this
->created));
// bind values
$stmt
->bindParam(
":name"
,
$this
->name);
$stmt
->bindParam(
":price"
,
$this
->price);
$stmt
->bindParam(
":description"
,
$this
->description);
$stmt
->bindParam(
":category_id"
,
$this
->category_id);
$stmt
->bindParam(
":created"
,
$this
->created);
// execute query
if
(
$stmt
->execute()){
return
true;
}
return
false;
}
5.3 출력
제품이 성공적으로 생성되었는지 테스트하려면 POSTMAN을 엽니 다. 요청 URL로 다음을 입력하십시오.
{ "name" : "Amazing Pillow 2.0", "price" : "199", "description" : "The best pillow for amazing programmers.", "category_id" : 2, "created" : "2018-06-01 00:35:07" } |
6.0 하나의 제품 읽기
6.1 read_one.php 파일 생성
<?php
// required headers
header(
"Access-Control-Allow-Origin: *"
);
header(
"Access-Control-Allow-Headers: access"
);
header(
"Access-Control-Allow-Methods: GET"
);
header(
"Access-Control-Allow-Credentials: true"
);
header(
'Content-Type: application/json'
);
// include database and object files
include_once
'../config/database.php'
;
include_once
'../objects/product.php'
;
// get database connection
$database
=
new
Database();
$db
=
$database
->getConnection();
// prepare product object
$product
=
new
Product(
$db
);
// set ID property of record to read
$product
->id = isset(
$_GET
[
'id'
]) ?
$_GET
[
'id'
] :
die
();
// read the details of product to be edited
$product
->readOne();
if
(
$product
->name!=null){
// create array
$product_arr
=
array
(
"id"
=>
$product
->id,
"name"
=>
$product
->name,
"description"
=>
$product
->description,
"price"
=>
$product
->price,
"category_id"
=>
$product
->category_id,
"category_name"
=>
$product
->category_name
);
// set response code - 200 OK
http_response_code(200);
// make it json format
echo
json_encode(
$product_arr
);
}
else
{
// set response code - 404 Not found
http_response_code(404);
// tell the user product does not exist
echo
json_encode(
array
(
"message"
=>
"Product does not exist."
));
}
?>
6.2 제품 readOne() 메서드
objects 폴더를 엽니다.
product.php 파일을 엽니다.
이전 섹션은 Product 클래스 내에서 다음 코드가 없으면 작동하지 않습니다.
// used when filling up the update product form
function
readOne(){
// query to read single record
$query
= "SELECT
c.name
as
category_name, p.id, p.name, p.description, p.price, p.category_id, p.created
FROM
" . $this->table_name . "
p
LEFT JOIN
categories c
ON p.category_id = c.id
WHERE
p.id = ?
LIMIT
0,1";
// prepare query statement
$stmt
=
$this
->conn->prepare(
$query
);
// bind id of product to be updated
$stmt
->bindParam(1,
$this
->id);
// execute query
$stmt
->execute();
// get retrieved row
$row
=
$stmt
->fetch(PDO::FETCH_ASSOC);
// set values to object properties
$this
->name =
$row
[
'name'
];
$this
->price =
$row
[
'price'
];
$this
->description =
$row
[
'description'
];
$this
->category_id =
$row
[
'category_id'
];
$this
->category_name =
$row
[
'category_name'
];
}
6.3 출력
다음으로 존재하지 않는 제품을 테스트합니다. 요청 URL로 다음을 입력하십시오. 파란색 "보내기"버튼을 클릭합니다.
7.0 제품 업데이트
7.1 "update.php"파일 생성
<?php
// required headers
header(
"Access-Control-Allow-Origin: *"
);
header(
"Content-Type: application/json; charset=UTF-8"
);
header(
"Access-Control-Allow-Methods: POST"
);
header(
"Access-Control-Max-Age: 3600"
);
header(
"Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
);
// include database and object files
include_once
'../config/database.php'
;
include_once
'../objects/product.php'
;
// get database connection
$database
=
new
Database();
$db
=
$database
->getConnection();
// prepare product object
$product
=
new
Product(
$db
);
// get id of product to be edited
$data
= json_decode(
file_get_contents
(
"php://input"
));
// set ID property of product to be edited
$product
->id =
$data
->id;
// set product property values
$product
->name =
$data
->name;
$product
->price =
$data
->price;
$product
->description =
$data
->description;
$product
->category_id =
$data
->category_id;
// update the product
if
(
$product
->update()){
// set response code - 200 ok
http_response_code(200);
// tell the user
echo
json_encode(
array
(
"message"
=>
"Product was updated."
));
}
// if unable to update the product, tell the user
else
{
// set response code - 503 service unavailable
http_response_code(503);
// tell the user
echo
json_encode(
array
(
"message"
=>
"Unable to update product."
));
}
?>
7.2 제품 update() 메서드
objects 폴더를 엽니다.
product.php 파일을 엽니다.
이전 섹션은 Product 클래스 내에서 다음 코드가 없으면 작동하지 않습니다.
// update the product
function
update(){
// update query
$query
= "UPDATE
" . $this->table_name . "
SET
name = :name,
price = :price,
description = :description,
category_id = :category_id
WHERE
id = :id";
// prepare query statement
$stmt
=
$this
->conn->prepare(
$query
);
// sanitize
$this
->name=htmlspecialchars(
strip_tags
(
$this
->name));
$this
->price=htmlspecialchars(
strip_tags
(
$this
->price));
$this
->description=htmlspecialchars(
strip_tags
(
$this
->description));
$this
->category_id=htmlspecialchars(
strip_tags
(
$this
->category_id));
$this
->id=htmlspecialchars(
strip_tags
(
$this
->id));
// bind new values
$stmt
->bindParam(
':name'
,
$this
->name);
$stmt
->bindParam(
':price'
,
$this
->price);
$stmt
->bindParam(
':description'
,
$this
->description);
$stmt
->bindParam(
':category_id'
,
$this
->category_id);
$stmt
->bindParam(
':id'
,
$this
->id);
// execute the query
if
(
$stmt
->execute()){
return
true;
}
return
false;
}
7.3 출력
POSTMAN을 엽니다. 요청 URL로 다음을 입력하십시오.
{ "id" : "106" , "name" : "Amazing Pillow 3.0" , "price" : "255" , "description" : "The best pillow for amazing programmers." , "category_id" : 2, "created" : "2018-08-01 00:35:07" } |
제품 ID 106은 예시 일 뿐입니다. 데이터베이스에 있는 제품 ID를 지정해야 합니다.
데이터베이스에 없는 ID를 지정해도 제품이 업데이트 되었다고 표시 될 수 있습니다. 데이터베이스에서 아무것도 업데이트하지 않지만 쿼리가 구문 오류 없이 성공적으로 실행되었습니다.
이를 방지하려면 데이터베이스에 ID가 있는지 확인하는 추가 유효성 검사가 필요합니다. 이 기능은 아직 튜토리얼의 일부가 아닙니다.
8.0 제품 삭제
8.1 "delete.php"파일 생성
<?php
// required headers
header(
"Access-Control-Allow-Origin: *"
);
header(
"Content-Type: application/json; charset=UTF-8"
);
header(
"Access-Control-Allow-Methods: POST"
);
header(
"Access-Control-Max-Age: 3600"
);
header(
"Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
);
// include database and object file
include_once
'../config/database.php'
;
include_once
'../objects/product.php'
;
// get database connection
$database
=
new
Database();
$db
=
$database
->getConnection();
// prepare product object
$product
=
new
Product(
$db
);
// get product id
$data
= json_decode(
file_get_contents
(
"php://input"
));
// set product id to be deleted
$product
->id =
$data
->id;
// delete the product
if
(
$product
->
delete
()){
// set response code - 200 ok
http_response_code(200);
// tell the user
echo
json_encode(
array
(
"message"
=>
"Product was deleted."
));
}
// if unable to delete the product
else
{
// set response code - 503 service unavailable
http_response_code(503);
// tell the user
echo
json_encode(
array
(
"message"
=>
"Unable to delete product."
));
}
?>
8.2 제품 delete() 메서드
// delete the product
function
delete
(){
// delete query
$query
=
"DELETE FROM "
.
$this
->table_name .
" WHERE id = ?"
;
// prepare query
$stmt
=
$this
->conn->prepare(
$query
);
// sanitize
$this
->id=htmlspecialchars(
strip_tags
(
$this
->id));
// bind id of record to delete
$stmt
->bindParam(1,
$this
->id);
// execute query
if
(
$stmt
->execute()){
return
true;
}
return
false;
}
8.3 출력
POSTMAN을 엽니 다. 요청 URL로 다음을 입력하십시오.
{ "id" : "106" } |
시스템이 제품 삭제에 실패하면 출력은 다음과 같습니다.
9.0 제품 검색
9.1 "search.php"파일 생성
<?php
// required headers
header(
"Access-Control-Allow-Origin: *"
);
header(
"Content-Type: application/json; charset=UTF-8"
);
// include database and object files
include_once
'../config/core.php'
;
include_once
'../config/database.php'
;
include_once
'../objects/product.php'
;
// instantiate database and product object
$database
=
new
Database();
$db
=
$database
->getConnection();
// initialize object
$product
=
new
Product(
$db
);
// get keywords
$keywords
=isset(
$_GET
[
"s"
]) ?
$_GET
[
"s"
] :
""
;
// query products
$stmt
=
$product
->search(
$keywords
);
$num
=
$stmt
->rowCount();
// check if more than 0 record found
if
(
$num
>0){
// products array
$products_arr
=
array
();
$products_arr
[
"records"
]=
array
();
// retrieve our table contents
// fetch() is faster than fetchAll()
while
(
$row
=
$stmt
->fetch(PDO::FETCH_ASSOC)){
// extract row
// this will make $row['name'] to
// just $name only
extract(
$row
);
$product_item
=
array
(
"id"
=>
$id
,
"name"
=>
$name
,
"description"
=> html_entity_decode(
$description
),
"price"
=>
$price
,
"category_id"
=>
$category_id
,
"category_name"
=>
$category_name
);
array_push
(
$products_arr
[
"records"
],
$product_item
);
}
// set response code - 200 OK
http_response_code(200);
// show products data
echo
json_encode(
$products_arr
);
}
else
{
// set response code - 404 Not found
http_response_code(404);
// tell the user no products found
echo
json_encode(
array
(
"message"
=>
"No products found."
)
);
}
?>
9.2 search() 메서드 생성
// search products
function
search(
$keywords
){
// select all query
$query
= "SELECT
c.name
as
category_name, p.id, p.name, p.description, p.price, p.category_id, p.created
FROM
" . $this->table_name . "
p
LEFT JOIN
categories c
ON p.category_id = c.id
WHERE
p.name LIKE ? OR p.description LIKE ? OR c.name LIKE ?
ORDER BY
p.created DESC";
// prepare query statement
$stmt
=
$this
->conn->prepare(
$query
);
// sanitize
$keywords
=htmlspecialchars(
strip_tags
(
$keywords
));
$keywords
=
"%{$keywords}%"
;
// bind
$stmt
->bindParam(1,
$keywords
);
$stmt
->bindParam(2,
$keywords
);
$stmt
->bindParam(3,
$keywords
);
// execute query
$stmt
->execute();
return
$stmt
;
}
9.3 출력
POSTMAN을 엽니다. 요청 URL로 다음을 입력하십시오.
파란색 "보내기"버튼을 클릭합니다.
10.0 제품 페이징
10.1 "read_paging.php"파일 생성
<?php
// required headers
header(
"Access-Control-Allow-Origin: *"
);
header(
"Content-Type: application/json; charset=UTF-8"
);
// include database and object files
include_once
'../config/core.php'
;
include_once
'../shared/utilities.php'
;
include_once
'../config/database.php'
;
include_once
'../objects/product.php'
;
// utilities
$utilities
=
new
Utilities();
// instantiate database and product object
$database
=
new
Database();
$db
=
$database
->getConnection();
// initialize object
$product
=
new
Product(
$db
);
// query products
$stmt
=
$product
->readPaging(
$from_record_num
,
$records_per_page
);
$num
=
$stmt
->rowCount();
// check if more than 0 record found
if
(
$num
>0){
// products array
$products_arr
=
array
();
$products_arr
[
"records"
]=
array
();
$products_arr
[
"paging"
]=
array
();
// retrieve our table contents
// fetch() is faster than fetchAll()
while
(
$row
=
$stmt
->fetch(PDO::FETCH_ASSOC)){
// extract row
// this will make $row['name'] to
// just $name only
extract(
$row
);
$product_item
=
array
(
"id"
=>
$id
,
"name"
=>
$name
,
"description"
=> html_entity_decode(
$description
),
"price"
=>
$price
,
"category_id"
=>
$category_id
,
"category_name"
=>
$category_name
);
array_push
(
$products_arr
[
"records"
],
$product_item
);
}
// include paging
$total_rows
=
$product
->
count
();
$page_url
=
"{$home_url}product/read_paging.php?"
;
$paging
=
$utilities
->getPaging(
$page
,
$total_rows
,
$records_per_page
,
$page_url
);
$products_arr
[
"paging"
]=
$paging
;
// set response code - 200 OK
http_response_code(200);
// make it json format
echo
json_encode(
$products_arr
);
}
else
{
// set response code - 404 Not found
http_response_code(404);
// tell the user products does not exist
echo
json_encode(
array
(
"message"
=>
"No products found."
)
);
}
?>
10.2 "core.php"파일 생성
이 파일에는 홈 URL 및 페이지 매김 변수와 같은 핵심 구성이 포함되어 있습니다.
<?php
// show error reporting
ini_set
(
'display_errors'
, 1);
error_reporting
(E_ALL);
// home page url
// page given in URL parameter, default page is one
$page
= isset(
$_GET
[
'page'
]) ?
$_GET
[
'page'
] : 1;
// set number of records per page
$records_per_page
= 5;
// calculate for the query LIMIT clause
$from_record_num
= (
$records_per_page
*
$page
) -
$records_per_page
;
?>
10.3 "readPaging()"메서드 생성
// read products with pagination
public
function
readPaging(
$from_record_num
,
$records_per_page
){
// select query
$query
= "SELECT
c.name
as
category_name, p.id, p.name, p.description, p.price, p.category_id, p.created
FROM
" . $this->table_name . "
p
LEFT JOIN
categories c
ON p.category_id = c.id
ORDER BY p.created DESC
LIMIT ?, ?";
// prepare query statement
$stmt
=
$this
->conn->prepare(
$query
);
// bind variable values
$stmt
->bindParam(1,
$from_record_num
, PDO::PARAM_INT);
$stmt
->bindParam(2,
$records_per_page
, PDO::PARAM_INT);
// execute query
$stmt
->execute();
// return values from database
return
$stmt
;
}
10.4 "count()"메서드 생성
여전히 제품 클래스 (product.php 파일)에서 다음 메서드를 추가합니다. 페이지 매김 배열을 작성하려면 총 행이 필요합니다. '페이징'계산에 포함됩니다.
// used for paging products
public
function
count
(){
$query
=
"SELECT COUNT(*) as total_rows FROM "
.
$this
->table_name .
""
;
$stmt
=
$this
->conn->prepare(
$query
);
$stmt
->execute();
$row
=
$stmt
->fetch(PDO::FETCH_ASSOC);
return
$row
[
'total_rows'
];
}
10.5 "페이징"배열 가져 오기
<?php
class
Utilities{
public
function
getPaging(
$page
,
$total_rows
,
$records_per_page
,
$page_url
){
// paging array
$paging_arr
=
array
();
// button for first page
$paging_arr
[
"first"
] =
$page
>1 ?
"{$page_url}page=1"
:
""
;
// count all products in the database to calculate total pages
$total_pages
=
ceil
(
$total_rows
/
$records_per_page
);
// range of links to show
$range
= 2;
// display links to 'range of pages' around 'current page'
$initial_num
=
$page
-
$range
;
$condition_limit_num
= (
$page
+
$range
) + 1;
$paging_arr
[
'pages'
]=
array
();
$page_count
=0;
for
(
$x
=
$initial_num
;
$x
<
$condition_limit_num
;
$x
++){
// be sure '$x is greater than 0' AND 'less than or equal to the $total_pages'
if
((
$x
> 0) && (
$x
<=
$total_pages
)){
$paging_arr
[
'pages'
][
$page_count
][
"page"
]=
$x
;
$paging_arr
[
'pages'
][
$page_count
][
"url"
]=
"{$page_url}page={$x}"
;
$paging_arr
[
'pages'
][
$page_count
][
"current_page"
] =
$x
==
$page
?
"yes"
:
"no"
;
$page_count
++;
}
}
// button for last page
$paging_arr
[
"last"
] =
$page
<
$total_pages
?
"{$page_url}page={$total_pages}"
:
""
;
// json format
return
$paging_arr
;
}
}
?>
10.6 출력
POSTMAN을 엽니다. 요청 URL로 다음을 입력하십시오.
파란색 "보내기"버튼을 클릭합니다.
11.0 읽기 카테고리
11.1 "category.php"파일 생성
<?php
class
Category{
// database connection and table name
private
$conn
;
private
$table_name
=
"categories"
;
// object properties
public
$id
;
public
$name
;
public
$description
;
public
$created
;
public
function
__construct(
$db
){
$this
->conn =
$db
;
}
// used by select drop-down list
public
function
readAll(){
//select all data
$query
= "SELECT
id, name, description
FROM
" . $this->table_name . "
ORDER BY
name";
$stmt
=
$this
->conn->prepare(
$query
);
$stmt
->execute();
return
$stmt
;
}
}
?>
11.2 "read.php"파일 생성
<?php
// required header
header(
"Access-Control-Allow-Origin: *"
);
header(
"Content-Type: application/json; charset=UTF-8"
);
// include database and object files
include_once
'../config/database.php'
;
include_once
'../objects/category.php'
;
// instantiate database and category object
$database
=
new
Database();
$db
=
$database
->getConnection();
// initialize object
$category
=
new
Category(
$db
);
// query categorys
$stmt
=
$category
->read();
$num
=
$stmt
->rowCount();
// check if more than 0 record found
if
(
$num
>0){
// products array
$categories_arr
=
array
();
$categories_arr
[
"records"
]=
array
();
// retrieve our table contents
// fetch() is faster than fetchAll()
while
(
$row
=
$stmt
->fetch(PDO::FETCH_ASSOC)){
// extract row
// this will make $row['name'] to
// just $name only
extract(
$row
);
$category_item
=
array
(
"id"
=>
$id
,
"name"
=>
$name
,
"description"
=> html_entity_decode(
$description
)
);
array_push
(
$categories_arr
[
"records"
],
$category_item
);
}
// set response code - 200 OK
http_response_code(200);
// show categories data in json format
echo
json_encode(
$categories_arr
);
}
else
{
// set response code - 404 Not found
http_response_code(404);
// tell the user no categories found
echo
json_encode(
array
(
"message"
=>
"No categories found."
)
);
}
?>
11.3 범주 "read()"메서드 추가
// used by select drop-down list
public
function
read(){
//select all data
$query
= "SELECT
id, name, description
FROM
" . $this->table_name . "
ORDER BY
name";
$stmt
=
$this
->conn->prepare(
$query
);
$stmt
->execute();
return
$stmt
;
}
11.4 출력
POSTMAN을 엽니다. 요청 URL로 다음을 입력하십시오.
http://localhost/api/category/read.php
파란색 "보내기"버튼을 클릭합니다.
12.0 소스 코드 다운로드
먼저 위의 잘 설명 된 단계별 자습서를 따르고 공부하는 것이 좋습니다. 학습에 있어 경험을 능가하는 것은 없습니다.
하지만 최종 소스 코드도 볼 수 있다면 더 빨리 배울 수 있을 것입니다. 추가 가이드로 간주합니다.
그것이 당신에게 가져올 가치 또는 기술 업그레이드를 상상해보십시오. 직장, 프로젝트 또는 사업에서 얻을 수 있는 추가 수입. 당신이 절약하는 소중한 시간. 그것이 당신이 원하는 것이 아닙니까?
13.0 다음은 무엇입니까?
두 가지 옵션이 있습니다.
a. PHP의 REST API 인증 예제 – JWT 자습서에서 REST API 인증 (사용자 인터페이스 포함)을 수행하는 방법을 학습하여 기술을 한 단계 업그레이드하십시오.
b. 위의 자습서는 사용자 인터페이스없이 API 측면에 중점을 둡니다. AJAX CRUD Tutorial에서 데이터베이스 레코드 (사용자 인터페이스 포함)를 생성, 읽기, 업데이트 및 삭제하는 방법을 배웁니다.
14.0 관련 튜토리얼
시작하기
웹 프로그래밍의 기초를 배웁니다.
PHP 프로그래밍 튜토리얼
PHP로 멋진 것을 시작하세요!
REST API 튜토리얼
웹 개발의 새로운 세계에 오신 것을 환영합니다!
PHP 웹 앱 소스 코드
웹 앱을 빌드 하는 데 도움이 되는 스크립트입니다.
모듈 별 다운로드 :
더 많은 스크립트
유용 할 수 있는 더 많은 코드 예제!
등록된 댓글이 없습니다.