How to use PATCH for updating a simple database fi

2019-05-14 11:51发布

问题:

I am new to php and API and I am trying to learn the methods. But I am not able to perform PATCH or PUT to update my simple mysql database. I used the following code.

if(isset($_PATCH)){     
    $con = mysqli_connect("localhost", "root", "root","wordpress");
    $sql = "UPDATE trainsample SET Location = ('$_PATCH[Location]'), Data = ('$_PATCH[Data]') WHERE Name = ('$_PATCH[Name]')";
    mysqli_query($con,$sql);
    echo "Data Updated<br>";
}
else
{
    echo "Data Not found ";
}

I am using postman as REST client and try to sent data to update the fields. Any help is appreciated. Thank you in advance.

回答1:

I found a workaround using POST. I am a beginner, if there is a better way please respond.

<?php
if(isset($_POST)){  

    $con = mysqli_connect("localhost", "root", "root","wordpress");
    $sql = "UPDATE `trainsample` SET `Location`='".$_POST['Location']."', 
            `Data`='".$_POST['Data']."' WHERE `Name`='".$_POST['Name']."'";
    if (mysqli_query($con, $sql)) {
        echo "Record updated successfully";
    } 
    else {
        echo "Error updating record: " . mysqli_error($con);
    }

    mysqli_close($con);
}
else
{
    echo "Data Not found ";
}
?>


回答2:

The following is a fully functional REST server in PHP:

<?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');
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].'"');
}

// create SQL based on HTTP method
switch ($method) {
  case 'GET':
    $sql = "select * from `$table`".($key?" WHERE id=$key":''); break;
  case 'PUT':
  case 'PATCH':
    $sql = "update `$table` set $set where id=$key"; break;
  case 'POST':
    $sql = "insert into `$table` set $set"; break;
  case 'DELETE':
    $sql = "delete `$table` where id=$key"; break;
}

// excecute 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 '[';
  for ($i=0;$i<mysqli_num_rows($result);$i++) {
    echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
  }
  if (!$key) echo ']';
} elseif ($method == 'POST') {
  echo mysqli_insert_id($link);
} else {
  echo mysqli_affected_rows($link);
}

// close mysql connection
mysqli_close($link);

It does:

  • Support HTTP verbs GET, POST, PUT, PATCH and DELETE
  • Escape all data properly to avoid SQL injection
  • Handle null values correctly

source



标签: php mysql rest api