Функции обновления и удаления PHP не работают

#php

#php

Вопрос:

Использование архитектуры MVC для создания одностраничного CRUD-приложения. Чтение и запись работают, но обновление и удаление не работают. Насколько я понимаю, функция удаления должна быть привязана к REQUEST_METHOD GET, но я не уверен, есть ли она у меня в нужном месте (в инструкции switch) или она должна быть в большем GET if условном. Я понятия не имею, почему обновление не работает.

Файл модели

 <?php
class Model {
private $connection;
function __construct($conn) {
    # intialize sql connection variable
    $this->connection = $conn;
}

# generic read from database functionality
public function read($table, $fields = '*', $limit = 1000, $sort = 'ASC', $id = null, $id_field = null) {
    $sql = "";
    $fieldString = '';
    # create string from $fields array
    if(is_array($fields)) $fieldString = implode(',', $fields); // the $fields array is in the format ['FIELD_1_NAME', 'FIELD_2_NAME', 'FIELD_3_NAME'] which is converted to the sting 'FIELD_1_NAME, FIELD_2_NAME, FIELD_3_NAME' for the SQL query
    else $fieldString = $fields;

    if(is_null($id)) {
        # get all values from MyTable, use fields array to get requested # fields and sort parameter to sort
        $sql = "SELECT $fieldString FROM $table LIMIT $limit";
    } else {
        # get a single value by id
        $sql = "SELECT $fieldString FROM $table WHERE $id_field = $id";
    }
    # SQL String test
    # echo($sql);
    if($result = $this->connection->query($sql)) {
        $results = [];
        # Generating Results as an array of Objects
        while ($row= $result->fetch_object()) {
            $results[] = $row;
        }
        return $results;
    } else {
        return false;
    }
}

# generic write to database functionality
public function write($table, $fields, $args) {
    # create string from $args array
    $argString = implode('','', $args); // the $args array is in the format ['VALUE_1', ' VALUE_2', ' VALUE_3'] which is converted to the sting "'VALUE_1', 'VALUE_2', 'VALUE_3'" for the SQL query
    # create string from $fields array
    $fieldString = implode(',', $fields); // the $fields array is in the format ['FIELD_1_NAME', 'FIELD_2_NAME', 'FIELD_3_NAME'] which is converted to the sting 'FIELD_1_NAME, FIELD_2_NAME, FIELD_3_NAME' for the SQL query
    # creating the sql query
    $sql = "INSERT INTO $table ($fieldString) VALUES('$argString')";
    # SQL String test
    echo($sql);
    return($this->connection->query($sql));
}

public function update($table, $fields, $args, $id) {
    # update DB implementation
    $argString = implode('','', $args);
    $fieldString = implode(',', $fields);
    $sql = "UPDATE $table SET ($fieldString) VALUES('$argString') WHERE id=$id";
    echo $sql;
    return($this->connection->query($sql));
}

public function delete($id) {
    # delete DB implementation
    $sql = "DELETE FROM Players WHERE id=$id";
    return($this->connection->query($sql));
}
}
?>
  

Файл контроллера

 <?php
class Controller {
# instance of model class injected into the controller
private $model;

function __construct($model) {
    $this->model = $model;
}

# request handler method is responsible for handling all http requests
public function requestHandler($server, $get, $post, $session) {
    # call method based on request, an example is shown below
    # example API format :
    # url for get request format for get by id: index.php?get=usersamp;id=1
    # url for get request format for get all: index.php?get=usersamp;limit=10
    # use your own API here
    # handling GET requests
    if($server['REQUEST_METHOD'] == 'GET') {
        # replace the url parameters based on your API parameters
        if(!empty($get["get"])) {
            switch ($get["get"]) {
                case 'players':
                    echo $this->getPlayers($get["id"], $get["limit"], $get["sort"]);
                    break;
                case 'delete':
                    echo $this->deletePlayer($get["id"]);
                    break;
                default:
                    echo 'Error: Invalid Request';
                    break;
            }
        }
    }

    # handling POST requests
    elseif($server['REQUEST_METHOD'] == 'POST') {
    # if the ID_FIELD is empty it’s a create request
        if(empty($post['id'])) {
            # replace FIELD NAMES as per your field names in the database
            echo $this->addPlayer(['Player_Name', 'Age', 'City', 'Country', 'Gender', 'Handedness', 'Broom', 'Position', 'Team', 'Favorite_Color', 'Headshot'], [$post['Player_Name'], $post['Age'], $post['City'], $post['Country'], $post['Gender'], $post['Handedness'], $post['Broom'], $post['Position'], $post['Team'], $post['Favorite_Color'], $post['Headshot']]);
        }

        # if the ID_FIELD is not empty then it’s an update request
        else { 
            echo $this->updatePlayer(['Player_Name', 'Age', 'City', 'Country', 'Gender', 'Handedness', 'Broom', 'Position', 'Team', 'Favorite_Color', 'Headshot'], [$post['Player_Name'], $post['Age'], $post['City'], $post['Country'], $post['Gender'], $post['Handedness'], $post['Broom'], $post['Position'], $post['Team'], $post['Favorite_Color'], $post['Headshot']]);
        }
    }
}

# change function name to one that represents your table name 
private function getPlayers($id, $limit = 1000, $sort) {
    # get data from the model
    # replace TABLE_NAME with the table that is to be read
    # replace ID_FIELD with the name of the ID Field
    $data = $this->model->read('Players', '*', $limit, $sort, $id, 'id');
    # process/transform data or apply application logic
    # return data as JSON string
    return json_encode($data);
}

# change function name to one that represents your table name
private function addPlayer($fields, $values) {
    # replace TABLE_NAME with the table that is to be read
    return $this->model->write('Players', $fields, $values);
}

# implement update and delete
private function updatePlayer($table, $fields, $values, $id) {
    return $this->model->update($table, $fields, $values, $id);
}

private function deletePlayer($id) {
    return $this->model->delete('Players', $id);
}
}
?>
  

Любая помощь или понимание приветствуются.

Ответ №1:

Ваше UPDATE утверждение неверно. Правильный синтаксис:

 UPDATE table_name SET column_name = some_value WHERE some_condition
  

Комментарии:

1. $fieldString содержит все имена столбцов, так почему это не работает? Есть ли способ использовать $fieldString , а не перечислять каждую вещь?

2. Должно ли это на самом деле говорить $sql = "UPDATE $table SET ($fieldString) = VALUES('$argString') WHERE id=$id"; ?

3. Нет. Пожалуйста, посмотрите больше о SQL-операторах.

4. Есть ли у вас предложения о том, как отредактировать этот оператор sql на основе предоставленного мной кода?

5. Либо вы используете цикл и индивидуально обновляете таблицу на основе вашего массива значений, либо вручную записываете каждое назначение в один оператор update. Например: UPDATE table_name SET $fields[0] = $args[0], $fields[1] = $args[1] ...etc .