設定路由 application/config/routes.php
$route['api/v1/url/(:any)']['DELETE'] = 'api/v1/url/delete/$1';
寫Controller application/controllers/api/v1/url.php
public function delete($url_shorten) {
$database = $this->load->database('default',true); //設定database連線
$query = $database //檢查紀錄是否存在
->from('urls')
->where('url_shorten',$url_shorten)
->get();
if (!$query -> num_rows() > 0) { //不大於零: 不存在
http_response_code(404); //回應HTTP 404 Not Found
print_r(
json_encode(
array(
'status' => 'error',
'code' => 404,
'message' => 'not-found'
)
)
);
die();
}
$database //執行刪除
->where('url_shorten',$url_shorten)
->delete('urls');
$dberror = $database->error(); //try catch DB錯誤
if ($dberror['code'] != 00000) {
print_r(
json_encode(
array(
'status' => 'error',
'message' => 'an database error occurred',
'code' => $dberror['code'],
)
)
);
set_status_header(500,'Internal Server Error - An database error occurred'); //如果錯誤,回復http 500
} else {
print_r(
json_encode(
array(
'status' => 'success',
)
)
);
}
}