updated for PHP7 tests
This commit is contained in:
parent
e1406d6ba9
commit
e6b92de0c6
1 changed files with 24 additions and 22 deletions
|
|
@ -1,32 +1,34 @@
|
|||
<?php
|
||||
|
||||
|
||||
// get the HTTP method, path and body of the request
|
||||
$method = $_SERVER['REQUEST_METHOD'];
|
||||
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
|
||||
$input = json_decode(file_get_contents('php://input'),true);
|
||||
|
||||
|
||||
// connect to the mysql database
|
||||
$link = mysqli_connect('localhost', 'user', 'pass', 'dbname');
|
||||
$link = mysqli_connect('localhost', 'php-crud-api', 'php-crud-api', 'php-crud-api');
|
||||
mysqli_set_charset($link,'utf8');
|
||||
|
||||
|
||||
// retrieve the table and key from the path
|
||||
$table = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
|
||||
$key = array_shift($request)+0;
|
||||
|
||||
// escape the columns and values from the input object
|
||||
$columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($input));
|
||||
$values = array_map(function ($value) use ($link) {
|
||||
if ($value===null) return null;
|
||||
return mysqli_real_escape_string($link,(string)$value);
|
||||
},array_values($input));
|
||||
|
||||
// build the SET part of the SQL command
|
||||
$set = '';
|
||||
for ($i=0;$i<count($columns);$i++) {
|
||||
$set.=($i>0?',':'').'`'.$columns[$i].'`=';
|
||||
$set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
|
||||
|
||||
if ($input) {
|
||||
// escape the columns and values from the input object
|
||||
$columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($input));
|
||||
$values = array_map(function ($value) use ($link) {
|
||||
if ($value===null) return null;
|
||||
return mysqli_real_escape_string($link,(string)$value);
|
||||
},array_values($input));
|
||||
|
||||
// build the SET part of the SQL command
|
||||
$set = '';
|
||||
for ($i=0;$i<count($columns);$i++) {
|
||||
$set.=($i>0?',':'').'`'.$columns[$i].'`=';
|
||||
$set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// create SQL based on HTTP method
|
||||
switch ($method) {
|
||||
case 'GET':
|
||||
|
|
@ -38,16 +40,16 @@ switch ($method) {
|
|||
case 'DELETE':
|
||||
$sql = "delete `$table` where id=$key"; break;
|
||||
}
|
||||
|
||||
|
||||
// execute SQL statement
|
||||
$result = mysqli_query($link,$sql);
|
||||
|
||||
|
||||
// die if SQL statement failed
|
||||
if (!$result) {
|
||||
http_response_code(404);
|
||||
die(mysqli_error());
|
||||
}
|
||||
|
||||
|
||||
// print results, insert id or affected row count
|
||||
if ($method == 'GET') {
|
||||
if (!$key) echo '[';
|
||||
|
|
@ -60,6 +62,6 @@ if ($method == 'GET') {
|
|||
} else {
|
||||
echo mysqli_affected_rows($link);
|
||||
}
|
||||
|
||||
|
||||
// close mysql connection
|
||||
mysqli_close($link);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue