|
| 1 | +<?php |
| 2 | + |
| 3 | +// get the HTTP method, path and body of the request |
| 4 | +$method = $_SERVER['REQUEST_METHOD']; |
| 5 | +$request = explode('/', trim($_SERVER['PATH_INFO'],'/')); |
| 6 | +$input = json_decode(file_get_contents('php://input'),true); |
| 7 | +if (!$input) $input = array(); |
| 8 | + |
| 9 | +// connect to the mysql database |
| 10 | +$link = mysqli_connect('localhost', 'php-crud-api', 'php-crud-api', 'php-crud-api'); |
| 11 | +mysqli_set_charset($link,'utf8'); |
| 12 | + |
| 13 | +// retrieve the table and key from the path |
| 14 | +$table = preg_replace('/[^a-z0-9_]+/i','',array_shift($request)); |
| 15 | +$key = array_shift($request)+0; |
| 16 | + |
| 17 | +// escape the columns and values from the input object |
| 18 | +$columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($input)); |
| 19 | +$values = array_map(function ($value) use ($link) { |
| 20 | + if ($value===null) return null; |
| 21 | + return mysqli_real_escape_string($link,(string)$value); |
| 22 | +},array_values($input)); |
| 23 | + |
| 24 | +// build the SET part of the SQL command |
| 25 | +$set = ''; |
| 26 | +for ($i=0;$i<count($columns);$i++) { |
| 27 | + $set.=($i>0?',':'').'`'.$columns[$i].'`='; |
| 28 | + $set.=($values[$i]===null?'NULL':'"'.$values[$i].'"'); |
| 29 | +} |
| 30 | + |
| 31 | +// create SQL based on HTTP method |
| 32 | +switch ($method) { |
| 33 | + case 'GET': |
| 34 | + $sql = "select * from `$table`".($key?" WHERE id=$key":''); break; |
| 35 | + case 'PUT': |
| 36 | + $sql = "update `$table` set $set where id=$key"; break; |
| 37 | + case 'POST': |
| 38 | + $sql = "insert into `$table` set $set"; break; |
| 39 | + case 'DELETE': |
| 40 | + $sql = "delete from `$table` where id=$key"; break; |
| 41 | +} |
| 42 | + |
| 43 | +// execute SQL statement |
| 44 | +$result = mysqli_query($link,$sql); |
| 45 | + |
| 46 | +// die if SQL statement failed |
| 47 | +if (!$result) { |
| 48 | + http_response_code(404); |
| 49 | + die(mysqli_error($link)); |
| 50 | +} |
| 51 | + |
| 52 | +// print results, insert id or affected row count |
| 53 | +if ($method == 'GET') { |
| 54 | + if (!$key) echo '['; |
| 55 | + for ($i=0;$i<mysqli_num_rows($result);$i++) { |
| 56 | + echo ($i>0?',':'').json_encode(mysqli_fetch_object($result)); |
| 57 | + } |
| 58 | + if (!$key) echo ']'; |
| 59 | +} elseif ($method == 'POST') { |
| 60 | + echo mysqli_insert_id($link); |
| 61 | +} else { |
| 62 | + echo mysqli_affected_rows($link); |
| 63 | +} |
| 64 | + |
| 65 | +// close mysql connection |
| 66 | +mysqli_close($link); |
0 commit comments