Как использовать PATCH на PHP REST API в следующем сценарии? - PullRequest
0 голосов
/ 04 августа 2020

Я создаю api отдыха с кодом basi c php, и следующий код обновляет записи для одной из моих таблиц:

$conn = $this->conn;
$returnArr = array();

$query = 'UPDATE `items` SET `name` = ?, `description` = ? WHERE `itemID` = ?';
$stmt = $conn->prepare( $query );
$stmt->bind_param( 'ssi', $this->name, $this->description, $this->itemId );

$result = $stmt->execute();
if ( $result ) {
    $stmt->close();
    return true;
} else {
    $stmt->close();
    return false;
}

Итак, допустим, код обновляет ' столбцы таблицы элементов: «имя и описание» из следующего запроса, сделанного из внешнего интерфейса:

{
    "name": "Test item",
    "description": "Test description",
    "itemId" : 1
}

А что, если бы я хотел, чтобы мой код обновлял только имя, когда я отправляю только имя из внешнего интерфейса: end:

{
    "name": "Test item",
    "itemId" : 1
}

Что сейчас происходит, так это то, что описание обновляется с помощью NULL, поскольку $ this-> description имеет значение null (не инициализировано)

Как выполнить патч здесь с помощью простого базиса c PHP лог c?

Ответы [ 2 ]

1 голос
/ 04 августа 2020

Создайте динамику запроса c только для полей, которые вы хотите изменить.

Это может показаться немного сложным только для 2-3 значений, но если у вас большая структура (много столбцов / полей ) оно того стоит.

// The dynamic data
$data = json_decode('{
    "name": "Test item",
    "description": "Test description",
    "itemId" : 1
}', true);

// a list of allowed fields for the query
$allowedFields = ['name', 'description', 'itemId'];

// build a list of fields and values for the query
$fields = [];
$values = [];
$itemId = 0;

// Go thru data and check if it is in the allowed list
// Also special treatment for the itemId

foreach($data as $field => $value) {
    if(!in_array($field, $allowedFields)) continue;
    if($field == 'itemId') {
        $itemId = $value;
        continue;
    }
    $fields[] = "`$field` = ?";
    $values[] = $data[$field];
}

// Place the itemId as very last
$values[] = $itemId;

// Build the query string
$query = 'UPDATE `items` SET ' . join(', ', $fields) . ' WHERE `itemID` = ?';

// Prepare and execute with the values
$sth = $dbh->prepare($query);
$sth->execute($values);

UPDATE items SET name =?, description =? ГДЕ itemID =?

0 голосов
/ 04 августа 2020

Использовать процедуру сохранения в mysql и вызывать ее в PHP с каждым входом, содержащим NULL. Вы можете фильтровать, когда ввод равен нулю в mysql SP.

DELIMITER \\

CREATE PROCEDURE `Update_Info`(
  IN p_name varchar(64),
  IN p_description varchar(64),
  IN p_itemID INT
)
BEGIN    
  UPDATE items
  SET `name` = IF(p_name = '', `name`, p_name),
  `description` = IF(p_description = '', `description`, p_description)
  WHERE itemID = p_itemID;
END

и в php примерно так:

// calling stored procedure command
$sql = 'CALL sp_takes_string_returns_table(?,?,?)';

// prepare for execution of the stored procedure
$stmt = $pdo->prepare($sql);

// pass value to the command
$stmt->bind_param( 'ssi', $this->name, $this->description, $this->itemId );
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...